diff --git a/src/System.Management.Automation/engine/Attributes.cs b/src/System.Management.Automation/engine/Attributes.cs
index 873607d86..cd68824c2 100644
--- a/src/System.Management.Automation/engine/Attributes.cs
+++ b/src/System.Management.Automation/engine/Attributes.cs
@@ -19,13 +19,11 @@ namespace System.Management.Automation.Internal
/// Serves as the base class for Metadata attributes.
///
///
- /// PSSnapins may not create custom attributes derived directly from
- /// ,
- /// since it has no public constructor. Only the public subclasses
- /// and
- ///
- /// are available.
+ /// PSSnapins may not create custom attributes derived directly from ,
+ /// since it has no public constructor. Only the public subclasses
+ /// and are available.
///
+ ///
///
///
[AttributeUsage(AttributeTargets.All)]
@@ -43,13 +41,11 @@ namespace System.Management.Automation.Internal
/// Serves as the base class for Metadata attributes that serve as guidance to the parser and parameter binder.
///
///
- /// PSSnapins may not create custom attributes derived
- /// ,
- /// since it has no public constructor. Only the sealed public subclasses
- /// and
- ///
- /// are available.
+ /// PSSnapins may not create custom attributes derived from , since it
+ /// has no public constructor. Only the sealed public subclasses and
+ /// are available.
///
+ ///
///
///
[AttributeUsage(AttributeTargets.All)]
@@ -72,11 +68,10 @@ namespace System.Management.Automation
/// Serves as the base class for Validate attributes that validate parameter arguments.
///
///
- /// Argument validation attributes can be attached to
- /// and
- /// parameters to ensure that the Cmdlet or CmdletProvider will not
- /// be invoked with invalid values of the parameter. Existing
- /// validation attributes include ,
+ /// Argument validation attributes can be attached to and
+ /// parameters to ensure that the Cmdlet or CmdletProvider will
+ /// not be invoked with invalid values of the parameter. Existing validation attributes include
+ /// ,
/// ,
/// ,
/// ,
@@ -84,25 +79,15 @@ namespace System.Management.Automation
/// ,
/// , and
/// .
- ///
- /// PSSnapins wishing to create custom argument validation attributes
- /// should derive from
- ///
- /// and override the
- ///
- /// abstract method, after which they can apply the
+ /// PSSnapins wishing to create custom argument validation attributes should derive from
+ /// and override the
+ /// abstract method, after which they can apply the
/// attribute to their parameters.
- /// validates the argument
- /// as a whole. If the argument value is potentially an enumeration,
- /// you can derive from
- /// which will take care of unrolling the enumeration
- /// and validate each element individually.
- ///
- /// It is also recommended to override
- /// to return a readable string
- /// similar to the attribute declaration, for example
- /// "[ValidateRangeAttribute(5,10)]".
- ///
+ /// validates the argument as a whole. If the argument value may
+ /// be an enumerable, you can derive from
+ /// which will take care of unrolling the enumerable and validate each element individually.
+ /// It is also recommended to override to return a readable string
+ /// similar to the attribute declaration, for example "[ValidateRangeAttribute(5,10)]".
/// If this attribute is applied to a string parameter, the string command argument will be validated.
/// If this attribute is applied to a string[] parameter, the string[] command argument will be validated.
///
@@ -119,18 +104,12 @@ namespace System.Management.Automation
public abstract class ValidateArgumentsAttribute : CmdletMetadataAttribute
{
///
- /// Overridden by subclasses to implement the validation of the parameter arguments.
+ /// Verify that the value of is valid.
///
/// Argument value to validate.
///
- /// The engine APIs for the context under which the prerequisite is being
- /// evaluated.
+ /// The engine APIs for the context under which the prerequisite is being evaluated.
///
- ///
- /// Validate that the value of is valid,
- /// and throw
- /// if it is invalid.
- ///
/// Should be thrown for any validation failure.
protected abstract void Validate(object arguments, EngineIntrinsics engineIntrinsics);
@@ -139,22 +118,18 @@ namespace System.Management.Automation
///
/// Object to validate.
///
- /// The engine APIs for the context under which the prerequisite is being
- /// evaluated.
+ /// The engine APIs for the context under which the prerequisite is being evaluated.
///
- /// Bool true if the validate succeeded.
+ /// True if the validation succeeded.
///
- /// Whenever any exception occurs during data validate.
- /// All the system exceptions are wrapped in ValidationMetadataException
+ /// Whenever any exception occurs during data validation.
+ /// Additionally, all the system exceptions are wrapped in ValidationMetadataException.
///
/// For invalid arguments.
- internal void InternalValidate(object o, EngineIntrinsics engineIntrinsics)
- {
- Validate(o, engineIntrinsics);
- }
+ internal void InternalValidate(object o, EngineIntrinsics engineIntrinsics) => Validate(o, engineIntrinsics);
///
- /// Initializes a new instance of a class derived from ValidateArgumentsAttribute.
+ /// Initializes a new instance of a class derived from .
///
protected ValidateArgumentsAttribute()
{
@@ -162,36 +137,24 @@ namespace System.Management.Automation
}
///
- /// A variant of which
- /// unrolls enumeration values and validates each element
- /// individually.
+ /// A variant of which unrolls enumeration values and validates
+ /// each element individually.
///
///
- /// is like
- /// , except that if
- /// the argument value is an enumeration,
- /// will unroll
- /// the enumeration and validate each item individually.
- ///
+ /// is like ,
+ /// except that if the argument value is enumerable,
+ /// will unroll the enumeration and validate each item individually.
/// Existing enumerated validation attributes include
/// ,
/// ,
/// , and
/// .
- ///
- /// PSSnapins wishing to create custom enumerated argument validation attributes
- /// should derive from
- ///
- /// and override the
+ /// PSSnapins wishing to create custom enumerated argument validation attributes should derive from
+ /// and override the
///
- /// abstract method, after which they can apply the
- /// attribute to their parameters.
- ///
- /// It is also recommended to override
- /// to return a readable string
- /// similar to the attribute declaration, for example
- /// "[ValidateRangeAttribute(5,10)]".
- ///
+ /// abstract method, after which they can apply the attribute to their parameters.
+ /// It is also recommended to override to return a readable string
+ /// similar to the attribute declaration, for example "[ValidateRangeAttribute(5,10)]".
/// If this attribute is applied to a string parameter, the string command argument will be validated.
/// If this attribute is applied to a string[] parameter, each string command argument will be validated.
///
@@ -204,19 +167,18 @@ namespace System.Management.Automation
public abstract class ValidateEnumeratedArgumentsAttribute : ValidateArgumentsAttribute
{
///
- /// Initializes a new instance of a class derived from ValidateEnumeratedArgumentsAttribute.
+ /// Initializes a new instance of a class derived from .
///
protected ValidateEnumeratedArgumentsAttribute() : base()
{
}
+
///
- /// Overridden by subclasses to implement the validation of each parameter argument.
+ /// Abstract method to be overridden by subclasses, implementing the validation of each parameter argument.
///
///
- /// Validate that the value of
- /// is valid, and throw
- ///
- /// if it is invalid.
+ /// Validate that the value of is valid, and throw
+ /// if it is invalid.
///
/// One of the parameter arguments.
/// Should be thrown for any validation failure.
@@ -227,8 +189,7 @@ namespace System.Management.Automation
///
/// Object to validate.
///
- /// The engine APIs for the context under which the prerequisite is being
- /// evaluated.
+ /// The engine APIs for the context under which the prerequisite is being evaluated.
///
///
/// PSSnapins should override instead.
@@ -236,7 +197,7 @@ namespace System.Management.Automation
/// Should be thrown for any validation failure.
protected sealed override void Validate(object arguments, EngineIntrinsics engineIntrinsics)
{
- if (arguments == null || arguments == AutomationNull.Value)
+ if (LanguagePrimitives.IsNull(arguments))
{
throw new ValidationMetadataException(
"ArgumentIsEmpty",
@@ -343,24 +304,24 @@ namespace System.Management.Automation
public abstract class CmdletCommonMetadataAttribute : CmdletMetadataAttribute
{
///
- /// Gets and sets the cmdlet default parameter set.
+ /// Gets or sets the cmdlet default parameter set.
///
public string DefaultParameterSetName { get; set; }
///
- /// Gets and sets a Boolean value that indicates the Cmdlet supports ShouldProcess. By default
+ /// Gets or sets a Boolean value that indicates the Cmdlet supports ShouldProcess. By default
/// the value is false, meaning the cmdlet doesn't support ShouldProcess.
///
public bool SupportsShouldProcess { get; set; } = false;
///
- /// Gets and sets a Boolean value that indicates the Cmdlet supports Paging. By default
+ /// Gets or sets a Boolean value that indicates the Cmdlet supports Paging. By default
/// the value is false, meaning the cmdlet doesn't support Paging.
///
public bool SupportsPaging { get; set; } = false;
///
- /// Gets and sets a Boolean value that indicates the Cmdlet supports Transactions. By default
+ /// Gets or sets a Boolean value that indicates the Cmdlet supports Transactions. By default
/// the value is false, meaning the cmdlet doesn't support Transactions.
///
public bool SupportsTransactions
@@ -384,10 +345,9 @@ namespace System.Management.Automation
private ConfirmImpact _confirmImpact = ConfirmImpact.Medium;
///
- /// Gets and sets a ConfirmImpact value that indicates
- /// the "destructiveness" of the operation and when it
- /// should be confirmed. This should only be used when
- /// SupportsShouldProcess is specified.
+ /// Gets or sets a ConfirmImpact value that indicates the "destructiveness" of the operation
+ /// and when it should be confirmed. This should only be used when SupportsShouldProcess is
+ /// specified.
///
public ConfirmImpact ConfirmImpact
{
@@ -396,16 +356,14 @@ namespace System.Management.Automation
}
///
- /// Gets and sets a HelpUri value that indicates
- /// the location of online help. This is used by
- /// Get-Help to retrieve help content when -Online
- /// is specified.
+ /// Gets or sets a HelpUri value that indicates the location of online help. This is used by
+ /// Get-Help to retrieve help content when -Online is specified.
///
[SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings")]
public string HelpUri { get; set; } = string.Empty;
///
- /// Gets and sets the RemotingBehavior value that declares how this cmdlet should interact
+ /// Gets or sets the RemotingBehavior value that declares how this cmdlet should interact
/// with ambient remoting.
///
public RemotingCapability RemotingCapability { get; set; } = RemotingCapability.PowerShell;
@@ -438,12 +396,12 @@ namespace System.Management.Automation
// NounName,VerbName have to be Non-Null strings
if (string.IsNullOrEmpty(nounName))
{
- throw PSTraceSource.NewArgumentException("nounName");
+ throw PSTraceSource.NewArgumentException(nameof(nounName));
}
if (string.IsNullOrEmpty(verbName))
{
- throw PSTraceSource.NewArgumentException("verbName");
+ throw PSTraceSource.NewArgumentException(nameof(verbName));
}
NounName = nounName;
@@ -452,8 +410,8 @@ namespace System.Management.Automation
}
///
- /// Identifies PowerShell script code as behaving like a cmdlet and hence uses
- /// cmdlet parameter binding instead of script parameter binding.
+ /// Identifies PowerShell script code as behaving like a cmdlet and hence uses cmdlet parameter binding
+ /// instead of script parameter binding.
///
[AttributeUsage(AttributeTargets.Class)]
public class CmdletBindingAttribute : CmdletCommonMetadataAttribute
@@ -467,8 +425,7 @@ namespace System.Management.Automation
}
///
- /// OutputTypeAttribute is used to specify the type of objects output by a cmdlet
- /// or script.
+ /// OutputTypeAttribute is used to specify the type of objects output by a cmdlet or script.
///
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
[SuppressMessage("Microsoft.Design", "CA1019:DefineAccessorsForAttributeArguments")]
@@ -496,7 +453,7 @@ namespace System.Management.Automation
/// The types output by the cmdlet.
public OutputTypeAttribute(params Type[] type)
{
- if (type != null && type.Length > 0)
+ if (type?.Length > 0)
{
Type = new PSTypeName[type.Length];
for (int i = 0; i < type.Length; i++)
@@ -516,7 +473,7 @@ namespace System.Management.Automation
/// The types output by the cmdlet.
public OutputTypeAttribute(params string[] type)
{
- if (type != null && type.Length > 0)
+ if (type?.Length > 0)
{
Type = new PSTypeName[type.Length];
for (int i = 0; i < type.Length; i++)
@@ -539,9 +496,7 @@ namespace System.Management.Automation
///
/// Attributes implemented by a provider can use:
- ///
/// [OutputType(ProviderCmdlet='cmdlet', typeof(...))]
- ///
/// To specify the provider specific objects returned for a given cmdlet.
///
public string ProviderCmdlet { get; set; }
@@ -552,9 +507,9 @@ namespace System.Management.Automation
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] ParameterSetName
{
- get { return _parameterSetName ?? (_parameterSetName = new[] { ParameterAttribute.AllParameterSets }); }
+ get => _parameterSetName ?? (_parameterSetName = new[] { ParameterAttribute.AllParameterSets });
- set { _parameterSetName = value; }
+ set => _parameterSetName = value;
}
private string[] _parameterSetName;
@@ -577,7 +532,7 @@ namespace System.Management.Automation
#region Parsing guidelines Attributes
///
- /// Declares an alternative name for a parameter.
+ /// Declares an alternative name for a parameter, cmdlet, or function.
///
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)]
public sealed class AliasAttribute : ParsingBaseAttribute
@@ -587,13 +542,7 @@ namespace System.Management.Automation
///
/// Gets the alias names passed to the constructor.
///
- public IList AliasNames
- {
- get
- {
- return this.aliasNames;
- }
- }
+ public IList AliasNames { get => this.aliasNames; }
///
/// Initializes a new instance of the AliasAttribute class.
@@ -604,7 +553,7 @@ namespace System.Management.Automation
{
if (aliasNames == null)
{
- throw PSTraceSource.NewArgumentNullException("aliasNames");
+ throw PSTraceSource.NewArgumentNullException(nameof(aliasNames));
}
this.aliasNames = aliasNames;
@@ -648,12 +597,12 @@ namespace System.Management.Automation
#region Experimental Feature Related Properties
///
- /// Get name of the experimental feature this attribute is associated with.
+ /// Gets the name of the experimental feature this attribute is associated with.
///
public string ExperimentName { get; }
///
- /// Get action for engine to take when the experimental feature is enabled.
+ /// Gets the action for the engine to take when the experimental feature is enabled.
///
public ExperimentAction ExperimentAction { get; }
@@ -661,7 +610,7 @@ namespace System.Management.Automation
internal bool ToShow => EffectiveAction == ExperimentAction.Show;
///
- /// Get effective action to take at run time.
+ /// Gets the effective action to take at run time.
///
private ExperimentAction EffectiveAction
{
@@ -681,70 +630,62 @@ namespace System.Management.Automation
#endregion
///
- /// Gets and sets the parameter position. If not set, the parameter is named.
+ /// Gets or sets the parameter position.
+ /// If not set, the parameter is named.
///
public int Position { get; set; } = int.MinValue;
///
- /// Gets and sets the name of the parameter set this parameter belongs to. When
- /// it is not specified ParameterAttribute.AllParameterSets is assumed.
+ /// Gets or sets the name of the parameter set this parameter belongs to.
+ /// When it is not specified, is assumed.
///
public string ParameterSetName
{
- get { return _parameterSetName; }
+ get => _parameterSetName;
- set
- {
- _parameterSetName = value;
- if (string.IsNullOrEmpty(_parameterSetName))
- {
- _parameterSetName = ParameterAttribute.AllParameterSets;
- }
- }
+ set => _parameterSetName = string.IsNullOrEmpty(value) ? ParameterAttribute.AllParameterSets : value;
}
///
- /// Gets and sets a flag specifying if this parameter is Mandatory. When
- /// it is not specified, false is assumed and the parameter is considered optional.
+ /// Gets or sets a flag specifying if this parameter is Mandatory.
+ /// When it is not specified, false is assumed and the parameter is considered optional.
///
public bool Mandatory { get; set; } = false;
///
- /// 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.
+ /// Gets or 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; set; }
///
- /// 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
- /// is not specified, false is assumed.
+ /// Gets or 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 or an alias of the parameter.
+ /// When it is not specified, false is assumed.
///
public bool ValueFromPipelineByPropertyName { get; set; }
///
- /// Gets and sets a flag that specifies that the remaining command line parameters
- /// should be associated with this parameter in the form of an array. When it
- /// is not specified, false is assumed.
+ /// Gets or sets a flag that specifies that the remaining command line parameters should be
+ /// associated with this parameter in the form of an array.
+ /// When it is not specified, false is assumed.
///
public bool ValueFromRemainingArguments { get; set; } = false;
///
- /// Gets and sets a short description for this parameter, suitable for presentation as a tool tip.
+ /// Gets or sets a short description for this parameter, suitable for presentation as a tool tip.
///
/// For a null or empty value when setting.
public string HelpMessage
{
- get
- {
- return _helpMessage;
- }
+ get => _helpMessage;
set
{
if (string.IsNullOrEmpty(value))
{
- throw PSTraceSource.NewArgumentException("HelpMessage");
+ throw PSTraceSource.NewArgumentException(nameof(HelpMessage));
}
_helpMessage = value;
@@ -752,22 +693,19 @@ namespace System.Management.Automation
}
///
- /// Gets and sets the base name of the resource for a help message. When this field is specified,
- /// HelpMessageResourceId must also be specified.
+ /// Gets or sets the base name of the resource for a help message.
+ /// When this field is specified, HelpMessageResourceId must also be specified.
///
/// For a null or empty value when setting.
public string HelpMessageBaseName
{
- get
- {
- return _helpMessageBaseName;
- }
+ get => _helpMessageBaseName;
set
{
if (string.IsNullOrEmpty(value))
{
- throw PSTraceSource.NewArgumentException("HelpMessageBaseName");
+ throw PSTraceSource.NewArgumentException(nameof(HelpMessageBaseName));
}
_helpMessageBaseName = value;
@@ -775,22 +713,19 @@ namespace System.Management.Automation
}
///
- /// Gets and sets the Id of the resource for a help message. When this field is specified,
- /// HelpMessageBaseName must also be specified.
+ /// Gets or sets the Id of the resource for a help message.
+ /// When this field is specified, HelpMessageBaseName must also be specified.
///
/// For a null or empty value when setting.
public string HelpMessageResourceId
{
- get
- {
- return _helpMessageResourceId;
- }
+ get => _helpMessageResourceId;
set
{
if (string.IsNullOrEmpty(value))
{
- throw PSTraceSource.NewArgumentException("HelpMessageResourceId");
+ throw PSTraceSource.NewArgumentException(nameof(HelpMessageResourceId));
}
_helpMessageResourceId = value;
@@ -801,11 +736,8 @@ namespace System.Management.Automation
/// Indicates that this parameter should not be shown to the user in this like intellisense
/// This is primarily to be used in functions that are implementing the logic for dynamic keywords.
///
- public bool DontShow
- {
- get;
- set;
- }
+ public bool DontShow { get; set; }
+
}
///
@@ -832,7 +764,7 @@ namespace System.Management.Automation
{
if (string.IsNullOrEmpty(psTypeName))
{
- throw PSTraceSource.NewArgumentException("psTypeName");
+ throw PSTraceSource.NewArgumentException(nameof(psTypeName));
}
this.PSTypeName = psTypeName;
@@ -857,7 +789,7 @@ namespace System.Management.Automation
public sealed class PSDefaultValueAttribute : ParsingBaseAttribute
{
///
- /// Specify the default value of a command parameter. The PowerShell engine does not
+ /// Specify the default value of a command parameter. The PowerShell engine does not
/// use this value in any way, it exists for other tools that want to reflect on cmdlets.
///
public object Value { get; set; }
@@ -869,8 +801,8 @@ namespace System.Management.Automation
}
///
- /// Specify that the member is hidden for the purposes of cmdlets like Get-Member and
- /// that the member is not displayed by default by Format-* cmdlets.
+ /// Specify that the member is hidden for the purposes of cmdlets like Get-Member and that the
+ /// member is not displayed by default by Format-* cmdlets.
///
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Event)]
public sealed class HiddenAttribute : ParsingBaseAttribute
@@ -882,8 +814,8 @@ namespace System.Management.Automation
#region Data validate Attributes
///
- /// Validates that the length of each parameter argument's Length falls in the range
- /// specified by MinLength and MaxLength.
+ /// Validates that the length of each parameter argument's Length falls in the range specified by
+ /// and .
///
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public sealed class ValidateLengthAttribute : ValidateEnumeratedArgumentsAttribute
@@ -899,8 +831,8 @@ namespace System.Management.Automation
public int MaxLength { get; }
///
- /// Validates that the length of each parameter argument's Length falls in the range
- /// specified by MinLength and MaxLength.
+ /// Validates that the length of each parameter argument's Length falls in the range specified
+ /// by and .
///
/// Object to validate.
/// If is not a string
@@ -911,29 +843,35 @@ namespace System.Management.Automation
string objectString = element as string;
if (objectString == null)
{
- throw new ValidationMetadataException("ValidateLengthNotString",
- null, Metadata.ValidateLengthNotString);
+ throw new ValidationMetadataException(
+ "ValidateLengthNotString",
+ null,
+ Metadata.ValidateLengthNotString);
}
int len = objectString.Length;
if (len < MinLength)
{
- throw new ValidationMetadataException("ValidateLengthMinLengthFailure",
- null, Metadata.ValidateLengthMinLengthFailure,
+ throw new ValidationMetadataException(
+ "ValidateLengthMinLengthFailure",
+ null,
+ Metadata.ValidateLengthMinLengthFailure,
MinLength, len);
}
if (len > MaxLength)
{
- throw new ValidationMetadataException("ValidateLengthMaxLengthFailure",
- null, Metadata.ValidateLengthMaxLengthFailure,
+ throw new ValidationMetadataException(
+ "ValidateLengthMaxLengthFailure",
+ null,
+ Metadata.ValidateLengthMaxLengthFailure,
MaxLength, len);
}
}
///
- /// Initializes a new instance of the ValidateLengthAttribute class.
+ /// Initializes a new instance of the class.
///
/// Minimum required length.
/// Maximum required length.
@@ -943,18 +881,20 @@ namespace System.Management.Automation
{
if (minLength < 0)
{
- throw PSTraceSource.NewArgumentOutOfRangeException("minLength", minLength);
+ throw PSTraceSource.NewArgumentOutOfRangeException(nameof(minLength), minLength);
}
if (maxLength <= 0)
{
- throw PSTraceSource.NewArgumentOutOfRangeException("maxLength", maxLength);
+ throw PSTraceSource.NewArgumentOutOfRangeException(nameof(maxLength), maxLength);
}
if (maxLength < minLength)
{
- throw new ValidationMetadataException("ValidateLengthMaxLengthSmallerThanMinLength",
- null, Metadata.ValidateLengthMaxLengthSmallerThanMinLength);
+ throw new ValidationMetadataException(
+ "ValidateLengthMaxLengthSmallerThanMinLength",
+ null,
+ Metadata.ValidateLengthMaxLengthSmallerThanMinLength);
}
MinLength = minLength;
@@ -962,34 +902,34 @@ namespace System.Management.Automation
}
}
- ///
+ ///
/// Predefined range kind to use with ValidateRangeAttribute.
- ///
+ ///
public enum ValidateRangeKind
{
- ///
+ ///
/// Range is greater than 0.
- ///
+ ///
Positive,
- ///
+ ///
/// Range is greater than or equal to 0.
- ///
+ ///
NonNegative,
- ///
+ ///
/// Range is less than 0.
- ///
+ ///
Negative,
- ///
+ ///
/// Range is less than or equal to 0.
- ///
+ ///
NonPositive
}
///
- /// Validates that each parameter argument falls in the range
- /// specified by MinRange and MaxRange.
+ /// Validates that each parameter argument falls in the range specified by
+ /// and .
///
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public sealed class ValidateRangeAttribute : ValidateEnumeratedArgumentsAttribute
@@ -1022,14 +962,14 @@ namespace System.Management.Automation
private ValidateRangeKind? _rangeKind;
///
- /// Validates that each parameter argument falls in the range
- /// specified by MinRange and MaxRange.
+ /// Validates that each parameter argument falls in the range specified by
+ /// and .
///
/// Object to validate.
///
- /// Thrown if the object to be validated does not implement IComparable,
- /// if the element type is not the same of MinRange, MaxRange,
- /// or if the element is not between MinRange and MaxRange.
+ /// Thrown if the object to be validated does not implement ,
+ /// if the element type is not the same as MinRange/MaxRange, or if the element is not between
+ /// MinRange and MaxRange.
///
protected override void ValidateElement(object element)
{
@@ -1058,26 +998,26 @@ namespace System.Management.Automation
}
///
- /// Initializes a new instance of the ValidateRangeAttribute class.
+ /// Initializes a new instance of the class.
///
/// Minimum value of the range allowed.
/// Maximum value of the range allowed.
/// For invalid arguments.
///
- /// if maxRange has a different type than minRange
- /// if maxRange is smaller than minRange
- /// if maxRange, minRange are not IComparable
+ /// if has a different type than
+ /// if is smaller than
+ /// if , are not
///
public ValidateRangeAttribute(object minRange, object maxRange) : base()
{
if (minRange == null)
{
- throw PSTraceSource.NewArgumentNullException("minRange");
+ throw PSTraceSource.NewArgumentNullException(nameof(minRange));
}
if (maxRange == null)
{
- throw PSTraceSource.NewArgumentNullException("maxRange");
+ throw PSTraceSource.NewArgumentNullException(nameof(maxRange));
}
if (maxRange.GetType() != minRange.GetType())
@@ -1086,21 +1026,20 @@ namespace System.Management.Automation
_promotedType = GetCommonType(minRange.GetType(), maxRange.GetType());
if (_promotedType != null)
{
- object resultValue;
- if (LanguagePrimitives.TryConvertTo(minRange, _promotedType, out resultValue))
+ if (LanguagePrimitives.TryConvertTo(minRange, _promotedType, out object minResultValue)
+ && LanguagePrimitives.TryConvertTo(maxRange, _promotedType, out object maxResultValue))
{
- minRange = resultValue;
- if (LanguagePrimitives.TryConvertTo(maxRange, _promotedType, out resultValue))
- {
- maxRange = resultValue;
- failure = false;
- }
+ minRange = minResultValue;
+ maxRange = maxResultValue;
+ failure = false;
}
}
if (failure)
{
- throw new ValidationMetadataException("MinRangeNotTheSameTypeOfMaxRange", null,
+ throw new ValidationMetadataException(
+ "MinRangeNotTheSameTypeOfMaxRange",
+ null,
Metadata.ValidateRangeMinRangeMaxRangeType,
minRange.GetType().Name, maxRange.GetType().Name);
}
@@ -1110,24 +1049,26 @@ namespace System.Management.Automation
_promotedType = minRange.GetType();
}
+ // minRange and maxRange have the same type, so we just need to check one of them
_minComparable = minRange as IComparable;
- // minRange and maxRange have the same type, so we just need
- // to check one of them
if (_minComparable == null)
{
- throw new ValidationMetadataException("MinRangeNotIComparable", null,
+ throw new ValidationMetadataException(
+ "MinRangeNotIComparable",
+ null,
Metadata.ValidateRangeNotIComparable);
}
_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
+ // Thanks to the IComparable test above this will not throw. They have the same type and are IComparable.
if (_minComparable.CompareTo(maxRange) > 0)
{
- throw new ValidationMetadataException("MaxRangeSmallerThanMinRange",
- null, Metadata.ValidateRangeMaxRangeSmallerThanMinRange);
+ throw new ValidationMetadataException(
+ "MaxRangeSmallerThanMinRange",
+ null,
+ Metadata.ValidateRangeMaxRangeSmallerThanMinRange);
}
MinRange = minRange;
@@ -1135,8 +1076,8 @@ namespace System.Management.Automation
}
///
- /// Initializes a new instance of the ValidateRangeAttribute class
- /// this constructor uses a predefined ranged.
+ /// Initializes a new instance of the class.
+ /// This constructor uses a predefined .
///
public ValidateRangeAttribute(ValidateRangeKind kind) : base()
{
@@ -1152,8 +1093,7 @@ namespace System.Management.Automation
"ValidationRangeElementType",
innerException: null,
Metadata.ValidateRangeElementType,
- element.GetType().Name,
- typeof(int).Name);
+ element.GetType().Name, typeof(int).Name);
}
object resultValue;
@@ -1174,8 +1114,7 @@ namespace System.Management.Automation
"ValidationRangeElementType",
null,
Metadata.ValidateRangeElementType,
- element.GetType().Name,
- commonType.Name);
+ element.GetType().Name, commonType.Name);
}
switch (rangeKind)
@@ -1229,12 +1168,10 @@ namespace System.Management.Automation
private void ValidateRange(object element)
{
- // MinRange and maxRange have the same type, so we just need
- // to compare to one of them.
+ // MinRange and MaxRange have the same type, so we just need to compare to one of them.
if (element.GetType() != _promotedType)
{
- object resultValue;
- if (LanguagePrimitives.TryConvertTo(element, _promotedType, out resultValue))
+ if (LanguagePrimitives.TryConvertTo(element, _promotedType, out object resultValue))
{
element = resultValue;
}
@@ -1244,8 +1181,7 @@ namespace System.Management.Automation
"ValidationRangeElementType",
null,
Metadata.ValidateRangeElementType,
- element.GetType().Name,
- MinRange.GetType().Name);
+ element.GetType().Name, MinRange.GetType().Name);
}
}
@@ -1256,8 +1192,7 @@ namespace System.Management.Automation
"ValidateRangeTooSmall",
null,
Metadata.ValidateRangeSmallerThanMinRangeFailure,
- element.ToString(),
- MinRange.ToString());
+ element.ToString(), MinRange.ToString());
}
if (_maxComparable.CompareTo(element) < 0)
@@ -1266,8 +1201,7 @@ namespace System.Management.Automation
"ValidateRangeTooBig",
null,
Metadata.ValidateRangeGreaterThanMaxRangeFailure,
- element.ToString(),
- MaxRange.ToString());
+ element.ToString(), MaxRange.ToString());
}
}
@@ -1284,8 +1218,8 @@ namespace System.Management.Automation
}
else if ((int)opTypeCode <= (int)TypeCode.UInt32)
{
- // If one of the operands is signed, we need to promote to double if the value is negative. We aren't
- // checking the value, so we unconditionally promote to double.
+ // If one of the operands is signed, we need to promote to double if the value is negative.
+ // We aren't checking the value, so we unconditionally promote to double.
resultType = LanguagePrimitives.IsSignedInteger(minTypeCode) || LanguagePrimitives.IsSignedInteger(maxTypeCode)
? typeof(double) : typeof(uint);
}
@@ -1295,8 +1229,8 @@ namespace System.Management.Automation
}
else if ((int)opTypeCode <= (int)TypeCode.UInt64)
{
- // If one of the operands is signed, we need to promote to double if the value is negative. We aren't
- // checking the value, so we unconditionally promote to double.
+ // If one of the operands is signed, we need to promote to double if the value is negative.
+ // We aren't checking the value, so we unconditionally promote to double.
resultType = LanguagePrimitives.IsSignedInteger(minTypeCode) || LanguagePrimitives.IsSignedInteger(maxTypeCode)
? typeof(double) : typeof(ulong);
}
@@ -1314,7 +1248,7 @@ namespace System.Management.Automation
}
///
- /// Validates that each parameter argument matches the RegexPattern.
+ /// Validates that each parameter argument matches the .
///
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public sealed class ValidatePatternAttribute : ValidateEnumeratedArgumentsAttribute
@@ -1331,7 +1265,6 @@ namespace System.Management.Automation
///
/// Gets or sets the custom error message pattern that is displayed to the user.
- ///
/// The text representation of the object being validated and the validating regex is passed as
/// the first and second formatting parameters to the ErrorMessage formatting pattern.
///
@@ -1346,9 +1279,9 @@ namespace System.Management.Automation
/// Validates that each parameter argument matches the RegexPattern.
///
/// Object to validate.
- /// If is not a string
- /// that matches the pattern
- /// and for invalid arguments
+ ///
+ /// If is not a string that matches the pattern, and for invalid arguments.
+ ///
protected override void ValidateElement(object element)
{
if (element == null)
@@ -1360,20 +1293,23 @@ namespace System.Management.Automation
}
string objectString = element.ToString();
- Regex regex = null;
- regex = new Regex(RegexPattern, Options);
+ var regex = new Regex(RegexPattern, Options);
Match match = regex.Match(objectString);
if (!match.Success)
{
- var errorMessageFormat = string.IsNullOrEmpty(ErrorMessage) ? Metadata.ValidatePatternFailure : ErrorMessage;
- throw new ValidationMetadataException("ValidatePatternFailure",
- null, errorMessageFormat,
- objectString, RegexPattern);
+ var errorMessageFormat = string.IsNullOrEmpty(ErrorMessage)
+ ? Metadata.ValidatePatternFailure
+ : ErrorMessage;
+ throw new ValidationMetadataException(
+ "ValidatePatternFailure",
+ null,
+ errorMessageFormat,
+ objectString, RegexPattern);
}
}
///
- /// Initializes a new instance of the ValidatePatternAttribute class.
+ /// Initializes a new instance of the class.
///
/// Pattern string to match.
/// For invalid arguments.
@@ -1381,7 +1317,7 @@ namespace System.Management.Automation
{
if (string.IsNullOrEmpty(regexPattern))
{
- throw PSTraceSource.NewArgumentException("regexPattern");
+ throw PSTraceSource.NewArgumentException(nameof(regexPattern));
}
RegexPattern = regexPattern;
@@ -1395,7 +1331,6 @@ namespace System.Management.Automation
{
///
/// Gets or sets the custom error message that is displayed to the user.
- ///
/// The item being validated and the validating scriptblock is passed as the first and second
/// formatting argument.
///
@@ -1436,15 +1371,19 @@ namespace System.Management.Automation
if (!LanguagePrimitives.IsTrue(result))
{
- var errorMessageFormat = string.IsNullOrEmpty(ErrorMessage) ? Metadata.ValidateScriptFailure : ErrorMessage;
- throw new ValidationMetadataException("ValidateScriptFailure",
- null, errorMessageFormat,
- element, ScriptBlock);
+ var errorMessageFormat = string.IsNullOrEmpty(ErrorMessage)
+ ? Metadata.ValidateScriptFailure
+ : ErrorMessage;
+ throw new ValidationMetadataException(
+ "ValidateScriptFailure",
+ null,
+ errorMessageFormat,
+ element, ScriptBlock);
}
}
///
- /// Initializes a new instance of the ValidateScriptBlockAttribute class.
+ /// Initializes a new instance of the class.
///
/// Scriptblock to match.
/// For invalid arguments.
@@ -1452,7 +1391,7 @@ namespace System.Management.Automation
{
if (scriptBlock == null)
{
- throw PSTraceSource.NewArgumentException("scriptBlock");
+ throw PSTraceSource.NewArgumentException(nameof(scriptBlock));
}
ScriptBlock = scriptBlock;
@@ -1480,36 +1419,31 @@ namespace System.Management.Automation
///
/// Object to validate.
///
- /// The engine APIs for the context under which the validation is being
- /// evaluated.
+ /// The engine APIs for the context under which the validation is being evaluated.
///
///
- /// if the element is none of ICollection, IEnumerable, IList, IEnumerator
- /// if the element's length is not between MinLength and MAxLEngth
+ /// if the element is none of , ,
+ /// ,
+ /// if the element's length is not between and
///
protected override void Validate(object arguments, EngineIntrinsics engineIntrinsics)
{
UInt32 len = 0;
- IList il;
- ICollection ic;
- IEnumerable ie;
- IEnumerator ienumerator;
-
if (arguments == null || arguments == AutomationNull.Value)
{
// treat a nul list the same as an empty list
// with a count of zero.
len = 0;
}
- else if ((il = arguments as IList) != null)
+ else if (arguments is IList il)
{
len = (UInt32)il.Count;
}
- else if ((ic = arguments as ICollection) != null)
+ else if (arguments is ICollection ic)
{
len = (UInt32)ic.Count;
}
- else if ((ie = arguments as IEnumerable) != null)
+ else if (arguments is IEnumerable ie)
{
IEnumerator e = ie.GetEnumerator();
while (e.MoveNext())
@@ -1517,60 +1451,68 @@ namespace System.Management.Automation
len++;
}
}
- else if ((ienumerator = arguments as IEnumerator) != null)
+ else if (arguments is IEnumerator enumerator)
{
- while (ienumerator.MoveNext())
+ while (enumerator.MoveNext())
{
len++;
}
}
else
{
- // No conversion succeeded so throw and exception...
- throw new ValidationMetadataException("NotAnArrayParameter",
- null, Metadata.ValidateCountNotInArray);
+ // No conversion succeeded so throw an exception...
+ throw new ValidationMetadataException(
+ "NotAnArrayParameter",
+ null,
+ Metadata.ValidateCountNotInArray);
}
if (MinLength == MaxLength && len != MaxLength)
{
- throw new ValidationMetadataException("ValidateCountExactFailure",
- null, Metadata.ValidateCountExactFailure,
+ throw new ValidationMetadataException(
+ "ValidateCountExactFailure",
+ null,
+ Metadata.ValidateCountExactFailure,
MaxLength, len);
}
if (len < MinLength || len > MaxLength)
{
- throw new ValidationMetadataException("ValidateCountMinMaxFailure",
- null, Metadata.ValidateCountMinMaxFailure,
+ throw new ValidationMetadataException(
+ "ValidateCountMinMaxFailure",
+ null,
+ Metadata.ValidateCountMinMaxFailure,
MinLength, MaxLength, len);
}
}
///
- /// Initializes a new instance of the ValidateCountAttribute class.
+ /// Initializes a new instance of the class.
///
/// Minimum number of values required.
/// Maximum number of values required.
/// For invalid arguments.
///
- /// if minLength is greater than maxLength
+ /// if is greater than
///
public ValidateCountAttribute(int minLength, int maxLength)
{
if (minLength < 0)
{
- throw PSTraceSource.NewArgumentOutOfRangeException("minLength", minLength);
+ throw PSTraceSource.NewArgumentOutOfRangeException(nameof(minLength), minLength);
}
if (maxLength <= 0)
{
- throw PSTraceSource.NewArgumentOutOfRangeException("maxLength", maxLength);
+ throw PSTraceSource.NewArgumentOutOfRangeException(nameof(maxLength), maxLength);
}
if (maxLength < minLength)
{
- throw new ValidationMetadataException("ValidateRangeMaxLengthSmallerThanMinLength",
- null, Metadata.ValidateCountMaxLengthSmallerThanMinLength);
+ throw new ValidationMetadataException(
+ "ValidateRangeMaxLengthSmallerThanMinLength",
+ null,
+ Metadata.ValidateCountMaxLengthSmallerThanMinLength);
}
MinLength = minLength;
@@ -1579,7 +1521,8 @@ namespace System.Management.Automation
}
///
- /// Optional base class for implementations that want a default implementation to cache valid values.
+ /// Optional base class for implementations that want a default
+ /// implementation to cache valid values.
///
public abstract class CachedValidValuesGeneratorBase : IValidateSetValuesGenerator
{
@@ -1588,9 +1531,11 @@ namespace System.Management.Automation
private int _validValuesCacheExpiration;
///
- /// Initializes a new instance of the CachedValidValuesGeneratorBase class.
+ /// Initializes a new instance of the class.
///
- /// Sets a time interval in seconds to reset the '_validValues' dynamic valid values cache.
+ ///
+ /// Sets a time interval in seconds to reset the dynamic valid values cache.
+ ///
protected CachedValidValuesGeneratorBase(int cacheExpirationInSeconds)
{
_validValuesCacheExpiration = cacheExpirationInSeconds;
@@ -1640,19 +1585,19 @@ namespace System.Management.Automation
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public sealed class ValidateSetAttribute : ValidateEnumeratedArgumentsAttribute
{
- // We can use either static '_validValues'
- // or dynamic valid values list generated by instance of 'validValuesGenerator'.
+ // We can use either static '_validValues' or dynamic valid values list generated by instance
+ // of 'validValuesGenerator'.
private string[] _validValues;
private IValidateSetValuesGenerator validValuesGenerator = null;
// The valid values generator cache works across 'ValidateSetAttribute' instances.
- private static ConcurrentDictionary s_ValidValuesGeneratorCache = new ConcurrentDictionary();
+ private static ConcurrentDictionary s_ValidValuesGeneratorCache =
+ new ConcurrentDictionary();
///
- /// Gets or sets the custom error message that is displayed to the user
- ///
- /// The item being validated and a text representation of the validation set
- /// is passed as the first and second formatting argument to the ErrorMessage formatting pattern.
+ /// Gets or sets the custom error message that is displayed to the user.
+ /// The item being validated and a text representation of the validation set is passed as the
+ /// first and second formatting argument to the formatting pattern.
///
///
/// [ValidateSet("A","B","C", ErrorMessage="The item '{0}' is not part of the set '{1}'.")
@@ -1662,8 +1607,8 @@ namespace System.Management.Automation
public string ErrorMessage { get; set; }
///
- /// Gets a flag specifying if we should ignore the case when performing string comparison. The
- /// default is true.
+ /// Gets a flag specifying if we should ignore the case when performing string comparison.
+ /// The default is true.
///
public bool IgnoreCase { get; set; } = true;
@@ -1706,36 +1651,35 @@ namespace System.Management.Automation
if (element == null)
{
throw new ValidationMetadataException(
- "ArgumentIsEmpty",
- null,
- Metadata.ValidateNotNullFailure);
+ "ArgumentIsEmpty",
+ null,
+ Metadata.ValidateNotNullFailure);
}
string objString = element.ToString();
foreach (string setString in ValidValues)
{
if (CultureInfo.InvariantCulture.CompareInfo.Compare(
- setString,
- objString,
- IgnoreCase ? CompareOptions.IgnoreCase : CompareOptions.None) == 0)
+ setString,
+ objString,
+ IgnoreCase ? CompareOptions.IgnoreCase : CompareOptions.None) == 0)
{
return;
}
}
var errorMessageFormat = string.IsNullOrEmpty(ErrorMessage) ? Metadata.ValidateSetFailure : ErrorMessage;
- throw new ValidationMetadataException("ValidateSetFailure", null,
+ throw new ValidationMetadataException(
+ "ValidateSetFailure",
+ null,
errorMessageFormat,
element.ToString(), SetAsString());
}
- private string SetAsString()
- {
- return string.Join(CultureInfo.CurrentUICulture.TextInfo.ListSeparator, ValidValues);
- }
+ private string SetAsString() => string.Join(CultureInfo.CurrentUICulture.TextInfo.ListSeparator, ValidValues);
///
- /// Initializes a new instance of the ValidateSetAttribute class.
+ /// Initializes a new instance of the class.
///
/// List of valid values.
/// For null arguments.
@@ -1744,45 +1688,50 @@ namespace System.Management.Automation
{
if (validValues == null)
{
- throw PSTraceSource.NewArgumentNullException("validValues");
+ throw PSTraceSource.NewArgumentNullException(nameof(validValues));
}
if (validValues.Length == 0)
{
- throw PSTraceSource.NewArgumentOutOfRangeException("validValues", validValues);
+ throw PSTraceSource.NewArgumentOutOfRangeException(nameof(validValues), validValues);
}
_validValues = validValues;
}
///
- /// Initializes a new instance of the ValidateSetAttribute class.
- /// Valid values is returned dynamically from a custom class implementing 'IValidateSetValuesGenerator' interface.
+ /// Initializes a new instance of the class.
+ /// Valid values are returned dynamically from a custom class implementing
+ ///
///
- /// Class that implements the 'IValidateSetValuesGenerator' interface.
+ ///
+ /// Class that implements the interface.
+ ///
/// For null arguments.
public ValidateSetAttribute(Type valuesGeneratorType)
{
- // We check 'IsNotPublic' because we don't want allow 'Activator.CreateInstance' create an instance of non-public type.
- if (!typeof(IValidateSetValuesGenerator).IsAssignableFrom(valuesGeneratorType) || valuesGeneratorType.IsNotPublic)
+ // We check 'IsNotPublic' because we don't want allow 'Activator.CreateInstance' create an
+ // instance of non-public type.
+ if (!typeof(IValidateSetValuesGenerator).IsAssignableFrom(
+ valuesGeneratorType) || valuesGeneratorType.IsNotPublic)
{
- throw PSTraceSource.NewArgumentException("valuesGeneratorType");
+ throw PSTraceSource.NewArgumentException(nameof(valuesGeneratorType));
}
// Add a valid values generator to the cache.
- // We don't cache valid values.
- // We expect that valid values can be cached in the valid values generator.
- validValuesGenerator = s_ValidValuesGeneratorCache.GetOrAdd(valuesGeneratorType, (key) => (IValidateSetValuesGenerator)Activator.CreateInstance(key));
+ // We don't cache valid values; we expect that valid values will be cached in the generator.
+ validValuesGenerator = s_ValidValuesGeneratorCache.GetOrAdd(
+ valuesGeneratorType, (key) => (IValidateSetValuesGenerator)Activator.CreateInstance(key));
}
}
///
- /// Allows dynamically generate set of values for ValidateSetAttribute.
+ /// Allows dynamically generate set of values for
///
public interface IValidateSetValuesGenerator
{
///
- /// Get a valid values.
+ /// Gets valid values.
///
string[] GetValidValues();
}
@@ -1798,8 +1747,7 @@ namespace System.Management.Automation
///
/// Object to validate.
///
- /// The engine APIs for the context under which the validation is being
- /// evaluated.
+ /// The engine APIs for the context under which the validation is being evaluated.
///
///
/// if the argument is untrusted.
@@ -1811,7 +1759,11 @@ namespace System.Management.Automation
{
if (ExecutionContext.IsMarkedAsUntrusted(arguments))
{
- throw new ValidationMetadataException("ValidateTrustedDataFailure", null, Metadata.ValidateTrustedDataFailure, arguments);
+ throw new ValidationMetadataException(
+ "ValidateTrustedDataFailure",
+ null,
+ Metadata.ValidateTrustedDataFailure,
+ arguments);
}
}
}
@@ -1826,7 +1778,7 @@ namespace System.Management.Automation
public sealed class AllowNullAttribute : CmdletMetadataAttribute
{
///
- /// Initializes a new instance of the AllowNullAttribute class.
+ /// Initializes a new instance of the class.
///
public AllowNullAttribute() { }
}
@@ -1838,7 +1790,7 @@ namespace System.Management.Automation
public sealed class AllowEmptyStringAttribute : CmdletMetadataAttribute
{
///
- /// Initializes a new instance of the AllowEmptyStringAttribute class.
+ /// Initializes a new instance of the class.
///
public AllowEmptyStringAttribute() { }
}
@@ -1850,7 +1802,7 @@ namespace System.Management.Automation
public sealed class AllowEmptyCollectionAttribute : CmdletMetadataAttribute
{
///
- /// Initializes a new instance of the AllowEmptyCollectionAttribute class.
+ /// Initializes a new instance of the class.
///
public AllowEmptyCollectionAttribute() { }
}
@@ -1870,23 +1822,17 @@ namespace System.Management.Automation
///
/// Gets the values in the set.
///
- public IList ValidRootDrives
- {
- get
- {
- return _validRootDrives;
- }
- }
+ public IList ValidRootDrives { get => _validRootDrives; }
///
- /// Initializes a new instance of the ValidateDrivePath class.
+ /// Initializes a new instance of the class.
///
/// List of approved root drives for path.
public ValidateDriveAttribute(params string[] validRootDrives)
{
if (validRootDrives == null)
{
- throw PSTraceSource.NewArgumentException("validRootDrives");
+ throw PSTraceSource.NewArgumentException(nameof(validRootDrives));
}
_validRootDrives = validRootDrives;
@@ -1902,9 +1848,9 @@ namespace System.Management.Automation
if (arguments == null)
{
throw new ValidationMetadataException(
- "PathArgumentIsEmpty",
- null,
- Metadata.ValidateNotNullFailure);
+ "PathArgumentIsEmpty",
+ null,
+ Metadata.ValidateNotNullFailure);
}
var path = arguments as string;
@@ -1916,14 +1862,12 @@ namespace System.Management.Automation
Metadata.ValidateDrivePathArgNotString);
}
- ProviderInfo providerInfo;
- PSDriveInfo driveInfo;
var resolvedPath = engineIntrinsics.SessionState.Internal.Globber.GetProviderPath(
path: path,
context: new CmdletProviderContext(engineIntrinsics.SessionState.Internal.ExecutionContext),
isTrusted: true,
- provider: out providerInfo,
- drive: out driveInfo);
+ provider: out ProviderInfo providerInfo,
+ drive: out PSDriveInfo driveInfo);
string rootDrive = driveInfo.Name;
if (string.IsNullOrEmpty(rootDrive))
@@ -1949,7 +1893,8 @@ namespace System.Management.Automation
throw new ValidationMetadataException(
"PathRootInvalid",
null,
- Metadata.ValidateDrivePathFailure, rootDrive, ValidDriveListAsString());
+ Metadata.ValidateDrivePathFailure,
+ rootDrive, ValidDriveListAsString());
}
}
@@ -1966,11 +1911,12 @@ namespace System.Management.Automation
public sealed class ValidateUserDriveAttribute : ValidateDriveAttribute
{
///
- /// Initializes a new instance of the ValidateUserDrivePathAttribute class.
+ /// Initializes a new instance of the class.
///
public ValidateUserDriveAttribute()
: base(new string[] { "User" })
- { }
+ {
+ }
}
#endregion
@@ -2012,16 +1958,12 @@ namespace System.Management.Automation
public sealed class ValidateNotNullAttribute : NullValidationAttributeBase
{
///
- /// Verifies the argument is not null and if it is a collection, that each
+ /// Verifies the argument is not null. If the argument is a collection, verifies that each
/// element in the collection is not null.
- /// If the argument is a collection then each element is validated.
///
- ///
- /// The arguments to verify.
- ///
+ /// The arguments to verify.
///
- /// The engine APIs for the context under which the validation is being
- /// evaluated.
+ /// The engine APIs for the context under which the validation is being evaluated.
///
///
/// true if the argument is valid.
@@ -2031,7 +1973,7 @@ namespace System.Management.Automation
///
protected override void Validate(object arguments, EngineIntrinsics engineIntrinsics)
{
- if (arguments == null || arguments == AutomationNull.Value)
+ if (LanguagePrimitives.IsNull(arguments))
{
throw new ValidationMetadataException(
"ArgumentIsNull",
@@ -2044,11 +1986,11 @@ namespace System.Management.Automation
// because a value-type value cannot be null.
if (isElementValueType) { return; }
- IEnumerator ienum = LanguagePrimitives.GetEnumerator(arguments);
- while (ienum.MoveNext())
+ IEnumerator enumerator = LanguagePrimitives.GetEnumerator(arguments);
+ while (enumerator.MoveNext())
{
- object element = ienum.Current;
- if (element == null || element == AutomationNull.Value)
+ object element = enumerator.Current;
+ if (LanguagePrimitives.IsNull(element))
{
throw new ValidationMetadataException(
"ArgumentIsNull",
@@ -2061,30 +2003,26 @@ namespace System.Management.Automation
}
///
- /// Validates that the parameters's argument is not null, is not
- /// an empty string, and is not an empty collection.
+ /// Validates that the parameters's argument is not null, is not an empty string, and is not
+ /// an empty collection.
///
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public sealed class ValidateNotNullOrEmptyAttribute : NullValidationAttributeBase
{
///
- /// Validates that the parameters's argument is not null, is not
- /// an empty string, and is not an empty collection. If arguments
- /// is a collection, each argument is verified.
+ /// Validates that the parameters's argument is not null, is not an empty string, and is
+ /// not an empty collection. If argument is a collection, each argument is verified.
///
- ///
- /// The arguments to verify.
- ///
+ /// The arguments to verify.
///
- /// The engine APIs for the context under which the validation is being
- /// evaluated.
+ /// The engine APIs for the context under which the validation is being evaluated.
///
///
- /// if the arguments are not valid
+ /// if the arguments are not valid.
///
protected override void Validate(object arguments, EngineIntrinsics engineIntrinsics)
{
- if (arguments == null || arguments == AutomationNull.Value)
+ if (LanguagePrimitives.IsNull(arguments))
{
throw new ValidationMetadataException(
"ArgumentIsNull",
@@ -2104,8 +2042,8 @@ namespace System.Management.Automation
else if (IsArgumentCollection(arguments.GetType(), out bool isElementValueType))
{
bool isEmpty = true;
- IEnumerator ienum = LanguagePrimitives.GetEnumerator(arguments);
- if (ienum.MoveNext()) { isEmpty = false; }
+ IEnumerator enumerator = LanguagePrimitives.GetEnumerator(arguments);
+ if (enumerator.MoveNext()) { isEmpty = false; }
// If the element of the collection is of value type, then no need to check for null
// because a value-type value cannot be null.
@@ -2113,8 +2051,8 @@ namespace System.Management.Automation
{
do
{
- object element = ienum.Current;
- if (element == null || element == AutomationNull.Value)
+ object element = enumerator.Current;
+ if (LanguagePrimitives.IsNull(element))
{
throw new ValidationMetadataException(
"ArgumentIsNull",
@@ -2132,7 +2070,7 @@ namespace System.Management.Automation
Metadata.ValidateNotNullOrEmptyCollectionFailure);
}
}
- } while (ienum.MoveNext());
+ } while (enumerator.MoveNext());
}
if (isEmpty)
@@ -2166,81 +2104,70 @@ namespace System.Management.Automation
/// Serves as the base class for attributes that perform argument transformation.
///
///
- /// Argument transformation attributes can be attached to
- /// and
- /// parameters to automatically transform the argument value in
- /// some fashion. The transformation might change the object,
- /// convert the type, or even load a file or AD object based on
- /// the name.
- /// Existing argument transformation attributes include
- /// .
- ///
- /// PSSnapins wishing to create custom argument transformation attributes
- /// should derive from
- ///
- /// and override the
- ///
- /// abstract method, after which they can apply the
- /// attribute to their parameters.
- ///
- /// It is also recommended to override
- /// to return a readable string
- /// similar to the attribute declaration, for example
- /// "[ValidateRangeAttribute(5,10)]".
- ///
- /// If multiple transformations are defined on a parameter,
- /// they will be invoked in series, each getting the output
- /// of the previous transformation.
+ /// Argument transformation attributes can be attached to and
+ /// parameters to automatically transform the argument
+ /// value in some fashion. The transformation might change the object, convert the type, or
+ /// even load a file or AD object based on the name. Existing argument transformation attributes
+ /// include .
+ /// Custom argument transformation attributes should derive from
+ /// and override the
+ /// abstract method, after which they
+ /// can apply the attribute to their parameters.
+ /// It is also recommended to override to return a readable
+ /// string similar to the attribute declaration, for example "[ValidateRangeAttribute(5,10)]".
+ /// If multiple transformations are defined on a parameter, they will be invoked in series,
+ /// each getting the output of the previous transformation.
///
///
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public abstract class ArgumentTransformationAttribute : CmdletMetadataAttribute
{
///
- /// Initializes a new instance of the ArgumentTransformationAttribute class.
+ /// Initializes a new instance of the class.
///
protected ArgumentTransformationAttribute()
{
}
///
- /// Method that will be overridden by the subclasses to transform the inputData parameter
- /// argument into some other object that will be used for the parameter's value.
+ /// Method that will be overridden by the subclasses to transform the
+ /// parameter argument into some other object that will be used for the parameter's value.
///
///
- /// The engine APIs for the context under which the transformation is being
- /// made.
+ /// The engine APIs for the context under which the transformation is being made.
///
/// Parameter argument to mutate.
- /// Mutated object(s).
- ///
- /// Return the transformed value of .
- /// Throw
- /// if the value of is invalid,
- /// and throw
- /// for other recoverable errors.
- ///
+ /// The transformed value(s) of .
/// Should be thrown for invalid arguments.
- /// Should be thrown for any problems during transformation.
+ ///
+ /// Should be thrown for any problems during transformation.
+ ///
public abstract object Transform(EngineIntrinsics engineIntrinsics, object inputData);
///
- /// Transform inputData and track the flow of untrusted object.
- /// NOTE: All internal handling of ArgumentTransformationAttribute should use this method to track the trustworthiness of
- /// the data input source by default.
+ /// Transform and track the flow of untrusted object.
+ /// NOTE: All internal handling of should use this method to
+ /// track the trustworthiness of the data input source by default.
///
///
- /// The default value for is True.
- /// You should stick to the default value for this parameter in most cases so that data input source is tracked during the transformation.
- /// The only acceptable exception is when this method is used in Compiler or Binder where you can generate extra code to track input source
- /// when it's necessary. This is to minimize the overhead when tracking is not needed.
+ /// The default value for is true.
+ /// You should stick to the default value for this parameter in most cases so that data input source is
+ /// tracked during the transformation. The only acceptable exception is when this method is used in
+ /// Compiler or Binder where you can generate extra code to track input source when it's necessary.
+ /// This is to minimize the overhead when tracking is not needed.
///
- internal object TransformInternal(EngineIntrinsics engineIntrinsics, object inputData, bool trackDataInputSource = true)
+ internal object TransformInternal(
+ EngineIntrinsics engineIntrinsics,
+ object inputData,
+ bool trackDataInputSource = true)
{
object result = Transform(engineIntrinsics, inputData);
if (trackDataInputSource && engineIntrinsics != null)
{
- ExecutionContext.PropagateInputSource(inputData, result, engineIntrinsics.SessionState.Internal.LanguageMode);
+ ExecutionContext.PropagateInputSource(
+ inputData,
+ result,
+ engineIntrinsics.SessionState.Internal.LanguageMode);
}
return result;
@@ -2251,7 +2178,7 @@ namespace System.Management.Automation
/// a) The parameter is not mandatory
/// b) The argument is null.
///
- public virtual bool TransformNullOptionalParameters { get { return true; } }
+ public virtual bool TransformNullOptionalParameters { get => true; }
}
#endregion Data Generation Attributes