File size: 27,439 Bytes
8c763fb | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;
namespace System.Management.Automation
{
/// <summary>
/// The metadata associated with a parameter.
/// </summary>
internal class CompiledCommandParameter
{
#region ctor
/// <summary>
/// Constructs an instance of the CompiledCommandAttribute using the specified
/// runtime-defined parameter.
/// </summary>
/// <param name="runtimeDefinedParameter">
/// A runtime defined parameter that contains the definition of the parameter and its metadata.
/// </param>
/// <param name="processingDynamicParameters">
/// True if dynamic parameters are being processed, or false otherwise.
/// </param>
/// <exception cref="ArgumentNullException">
/// If <paramref name="runtimeDefinedParameter"/> is null.
/// </exception>
/// <exception cref="MetadataException">
/// If the parameter has more than one <see cref="ParameterAttribute">ParameterAttribute</see>
/// that defines the same parameter-set name.
/// </exception>
internal CompiledCommandParameter(RuntimeDefinedParameter runtimeDefinedParameter, bool processingDynamicParameters)
{
if (runtimeDefinedParameter == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(runtimeDefinedParameter));
}
this.Name = runtimeDefinedParameter.Name;
this.Type = runtimeDefinedParameter.ParameterType;
this.IsDynamic = processingDynamicParameters;
this.CollectionTypeInformation = new ParameterCollectionTypeInformation(runtimeDefinedParameter.ParameterType);
this.CompiledAttributes = new Collection<Attribute>();
this.ParameterSetData = new Dictionary<string, ParameterSetSpecificMetadata>(StringComparer.OrdinalIgnoreCase);
Collection<ValidateArgumentsAttribute> validationAttributes = null;
Collection<ArgumentTransformationAttribute> argTransformationAttributes = null;
string[] aliases = null;
// First, process attributes that aren't type conversions
foreach (Attribute attribute in runtimeDefinedParameter.Attributes)
{
if (processingDynamicParameters)
{
// When processing dynamic parameters, the attribute list may contain experimental attributes
// and disabled parameter attributes. We should ignore those attributes.
// When processing non-dynamic parameters, the experimental attributes and disabled parameter
// attributes have already been filtered out when constructing the RuntimeDefinedParameter.
if (attribute is ExperimentalAttribute || attribute is ParameterAttribute param && param.ToHide)
{
continue;
}
}
if (attribute is not ArgumentTypeConverterAttribute)
{
ProcessAttribute(runtimeDefinedParameter.Name, attribute, ref validationAttributes, ref argTransformationAttributes, ref aliases);
}
}
// If this is a PSCredential type and they haven't added any argument transformation attributes,
// add one for credential transformation
if ((this.Type == typeof(PSCredential)) && argTransformationAttributes == null)
{
ProcessAttribute(runtimeDefinedParameter.Name, new CredentialAttribute(), ref validationAttributes, ref argTransformationAttributes, ref aliases);
}
// Now process type converters
foreach (var attribute in runtimeDefinedParameter.Attributes.OfType<ArgumentTypeConverterAttribute>())
{
ProcessAttribute(runtimeDefinedParameter.Name, attribute, ref validationAttributes, ref argTransformationAttributes, ref aliases);
}
this.ValidationAttributes = validationAttributes == null
? Array.Empty<ValidateArgumentsAttribute>()
: validationAttributes.ToArray();
this.ArgumentTransformationAttributes = argTransformationAttributes == null
? Array.Empty<ArgumentTransformationAttribute>()
: argTransformationAttributes.ToArray();
this.Aliases = aliases == null
? Array.Empty<string>()
: aliases.ToArray();
}
/// <summary>
/// Constructs an instance of the CompiledCommandAttribute using the reflection information retrieved
/// from the enclosing bindable object type.
/// </summary>
/// <param name="member">
/// The member information for the parameter
/// </param>
/// <param name="processingDynamicParameters">
/// True if dynamic parameters are being processed, or false otherwise.
/// </param>
/// <exception cref="ArgumentNullException">
/// If <paramref name="member"/> is null.
/// </exception>
/// <exception cref="ArgumentException">
/// If <paramref name="member"/> is not a field or a property.
/// </exception>
/// <exception cref="MetadataException">
/// If the member has more than one <see cref="ParameterAttribute">ParameterAttribute</see>
/// that defines the same parameter-set name.
/// </exception>
internal CompiledCommandParameter(MemberInfo member, bool processingDynamicParameters)
{
if (member == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(member));
}
this.Name = member.Name;
this.DeclaringType = member.DeclaringType;
this.IsDynamic = processingDynamicParameters;
var propertyInfo = member as PropertyInfo;
if (propertyInfo != null)
{
this.Type = propertyInfo.PropertyType;
}
else
{
var fieldInfo = member as FieldInfo;
if (fieldInfo != null)
{
this.Type = fieldInfo.FieldType;
}
else
{
ArgumentException e =
PSTraceSource.NewArgumentException(
nameof(member),
DiscoveryExceptions.CompiledCommandParameterMemberMustBeFieldOrProperty);
throw e;
}
}
this.CollectionTypeInformation = new ParameterCollectionTypeInformation(this.Type);
this.CompiledAttributes = new Collection<Attribute>();
this.ParameterSetData = new Dictionary<string, ParameterSetSpecificMetadata>(StringComparer.OrdinalIgnoreCase);
// We do not want to get the inherited custom attributes, only the attributes exposed
// directly on the member
var memberAttributes = member.GetCustomAttributes(false);
Collection<ValidateArgumentsAttribute> validationAttributes = null;
Collection<ArgumentTransformationAttribute> argTransformationAttributes = null;
string[] aliases = null;
foreach (Attribute attr in memberAttributes)
{
switch (attr)
{
case ExperimentalAttribute _:
case ParameterAttribute param when param.ToHide:
break;
default:
ProcessAttribute(member.Name, attr, ref validationAttributes, ref argTransformationAttributes, ref aliases);
break;
}
}
this.ValidationAttributes = validationAttributes == null
? Array.Empty<ValidateArgumentsAttribute>()
: validationAttributes.ToArray();
this.ArgumentTransformationAttributes = argTransformationAttributes == null
? Array.Empty<ArgumentTransformationAttribute>()
: argTransformationAttributes.ToArray();
this.Aliases = aliases ?? Array.Empty<string>();
}
#endregion ctor
/// <summary>
/// Gets the name of the parameter.
/// </summary>
internal string Name { get; }
/// <summary>
/// The PSTypeName from a PSTypeNameAttribute.
/// </summary>
internal string PSTypeName { get; private set; }
/// <summary>
/// Gets the Type information of the attribute.
/// </summary>
internal Type Type { get; }
/// <summary>
/// Gets the Type information of the attribute.
/// </summary>
internal Type DeclaringType { get; }
/// <summary>
/// Gets whether the parameter is a dynamic parameter or not.
/// </summary>
internal bool IsDynamic { get; }
/// <summary>
/// Gets the parameter collection type information.
/// </summary>
internal ParameterCollectionTypeInformation CollectionTypeInformation { get; }
/// <summary>
/// A collection of the attributes found on the member. The attributes have been compiled into
/// a format that easier to digest by the metadata processor.
/// </summary>
internal Collection<Attribute> CompiledAttributes { get; }
/// <summary>
/// Gets the collection of data generation attributes on this parameter.
/// </summary>
internal ArgumentTransformationAttribute[] ArgumentTransformationAttributes { get; }
/// <summary>
/// Gets the collection of data validation attributes on this parameter.
/// </summary>
internal ValidateArgumentsAttribute[] ValidationAttributes { get; }
/// <summary>
/// Get and private set the obsolete attribute on this parameter.
/// </summary>
internal ObsoleteAttribute ObsoleteAttribute { get; private set; }
/// <summary>
/// If true, null can be bound to the parameter even if the parameter is mandatory.
/// </summary>
internal bool AllowsNullArgument { get; private set; }
/// <summary>
/// If true, null cannot be bound to the parameter (ValidateNotNull
/// and/or ValidateNotNullOrEmpty has been specified).
/// </summary>
internal bool CannotBeNull { get; private set; }
/// <summary>
/// If true, an empty string can be bound to the string parameter
/// even if the parameter is mandatory.
/// </summary>
internal bool AllowsEmptyStringArgument { get; private set; }
/// <summary>
/// If true, an empty collection can be bound to the collection/array parameter
/// even if the parameter is mandatory.
/// </summary>
internal bool AllowsEmptyCollectionArgument { get; private set; }
/// <summary>
/// Gets or sets the value that tells whether this parameter
/// is for the "all" parameter set.
/// </summary>
internal bool IsInAllSets { get; set; }
/// <summary>
/// Returns true if this parameter is ValueFromPipeline or ValueFromPipelineByPropertyName
/// in one or more (but not necessarily all) parameter sets.
/// </summary>
internal bool IsPipelineParameterInSomeParameterSet { get; private set; }
/// <summary>
/// Returns true if this parameter is Mandatory in one or more (but not necessarily all) parameter sets.
/// </summary>
internal bool IsMandatoryInSomeParameterSet { get; private set; }
/// <summary>
/// Gets or sets the parameter set flags that map the parameter sets
/// for this parameter to the parameter set names.
/// </summary>
/// <remarks>
/// This is a bit-field that maps the parameter sets in this parameter
/// to the parameter sets for the rest of the command.
/// </remarks>
internal uint ParameterSetFlags { get; set; }
/// <summary>
/// A delegate that can set the property.
/// </summary>
internal Action<object, object> Setter { get; set; }
/// <summary>
/// A dictionary of the parameter sets and the parameter set specific data for this parameter.
/// </summary>
internal Dictionary<string, ParameterSetSpecificMetadata> ParameterSetData { get; }
/// <summary>
/// The alias names for this parameter.
/// </summary>
internal string[] Aliases { get; }
/// <summary>
/// Determines if this parameter takes pipeline input for any of the specified
/// parameter set flags.
/// </summary>
/// <param name="validParameterSetFlags">
/// The flags for the parameter sets to check to see if the parameter takes
/// pipeline input.
/// </param>
/// <returns>
/// True if the parameter takes pipeline input in any of the specified parameter
/// sets, or false otherwise.
/// </returns>
internal bool DoesParameterSetTakePipelineInput(uint validParameterSetFlags)
{
if (!IsPipelineParameterInSomeParameterSet)
{
return false;
}
// Loop through each parameter set the parameter is in to see if that parameter set is
// still valid. If so, and the parameter takes pipeline input in that parameter set,
// then return true
foreach (ParameterSetSpecificMetadata parameterSetData in ParameterSetData.Values)
{
if ((parameterSetData.IsInAllSets ||
(parameterSetData.ParameterSetFlag & validParameterSetFlags) != 0) &&
(parameterSetData.ValueFromPipeline ||
parameterSetData.ValueFromPipelineByPropertyName))
{
return true;
}
}
return false;
}
/// <summary>
/// Gets the parameter set data for this parameter for the specified parameter set.
/// </summary>
/// <param name="parameterSetFlag">
/// The parameter set to get the parameter set data for.
/// </param>
/// <returns>
/// The parameter set specified data for the specified parameter set.
/// </returns>
internal ParameterSetSpecificMetadata GetParameterSetData(uint parameterSetFlag)
{
ParameterSetSpecificMetadata result = null;
foreach (ParameterSetSpecificMetadata setData in ParameterSetData.Values)
{
// If the parameter is in all sets, then remember the data, but
// try to find a more specific match
if (setData.IsInAllSets)
{
result = setData;
}
else
{
if ((setData.ParameterSetFlag & parameterSetFlag) != 0)
{
result = setData;
break;
}
}
}
return result;
}
/// <summary>
/// Gets the parameter set data for this parameter for the specified parameter sets.
/// </summary>
/// <param name="parameterSetFlags">
/// The parameter sets to get the parameter set data for.
/// </param>
/// <returns>
/// A collection for all parameter set specified data for the parameter sets specified by
/// the <paramref name="parameterSetFlags"/>.
/// </returns>
internal IEnumerable<ParameterSetSpecificMetadata> GetMatchingParameterSetData(uint parameterSetFlags)
{
foreach (ParameterSetSpecificMetadata setData in ParameterSetData.Values)
{
// If the parameter is in all sets, then remember the data, but
// try to find a more specific match
if (setData.IsInAllSets)
{
yield return setData;
}
else
{
if ((setData.ParameterSetFlag & parameterSetFlags) != 0)
{
yield return setData;
}
}
}
}
#region helper methods
/// <summary>
/// Processes the Attribute metadata to generate a CompiledCommandAttribute.
/// </summary>
/// <exception cref="MetadataException">
/// If the attribute is a parameter attribute and another parameter attribute
/// has been processed with the same parameter-set name.
/// </exception>
private void ProcessAttribute(
string memberName,
Attribute attribute,
ref Collection<ValidateArgumentsAttribute> validationAttributes,
ref Collection<ArgumentTransformationAttribute> argTransformationAttributes,
ref string[] aliases)
{
if (attribute == null)
return;
CompiledAttributes.Add(attribute);
// Now process the attribute based on it's type
if (attribute is ParameterAttribute paramAttr)
{
ProcessParameterAttribute(memberName, paramAttr);
return;
}
ValidateArgumentsAttribute validateAttr = attribute as ValidateArgumentsAttribute;
if (validateAttr != null)
{
validationAttributes ??= new Collection<ValidateArgumentsAttribute>();
validationAttributes.Add(validateAttr);
if ((attribute is ValidateNotNullAttribute) || (attribute is ValidateNotNullOrEmptyAttribute))
{
this.CannotBeNull = true;
}
return;
}
AliasAttribute aliasAttr = attribute as AliasAttribute;
if (aliasAttr != null)
{
if (aliases == null)
{
aliases = aliasAttr.aliasNames;
}
else
{
var prevAliasNames = aliases;
var newAliasNames = aliasAttr.aliasNames;
aliases = new string[prevAliasNames.Length + newAliasNames.Length];
Array.Copy(prevAliasNames, aliases, prevAliasNames.Length);
Array.Copy(newAliasNames, 0, aliases, prevAliasNames.Length, newAliasNames.Length);
}
return;
}
ArgumentTransformationAttribute argumentAttr = attribute as ArgumentTransformationAttribute;
if (argumentAttr != null)
{
argTransformationAttributes ??= new Collection<ArgumentTransformationAttribute>();
argTransformationAttributes.Add(argumentAttr);
return;
}
AllowNullAttribute allowNullAttribute = attribute as AllowNullAttribute;
if (allowNullAttribute != null)
{
this.AllowsNullArgument = true;
return;
}
AllowEmptyStringAttribute allowEmptyStringAttribute = attribute as AllowEmptyStringAttribute;
if (allowEmptyStringAttribute != null)
{
this.AllowsEmptyStringArgument = true;
return;
}
AllowEmptyCollectionAttribute allowEmptyCollectionAttribute = attribute as AllowEmptyCollectionAttribute;
if (allowEmptyCollectionAttribute != null)
{
this.AllowsEmptyCollectionArgument = true;
return;
}
ObsoleteAttribute obsoleteAttr = attribute as ObsoleteAttribute;
if (obsoleteAttr != null)
{
ObsoleteAttribute = obsoleteAttr;
return;
}
PSTypeNameAttribute psTypeNameAttribute = attribute as PSTypeNameAttribute;
if (psTypeNameAttribute != null)
{
this.PSTypeName = psTypeNameAttribute.PSTypeName;
}
}
/// <summary>
/// Extracts the data from the ParameterAttribute and creates the member data as necessary.
/// </summary>
/// <param name="parameterName">
/// The name of the parameter.
/// </param>
/// <param name="parameter">
/// The instance of the ParameterAttribute to extract the data from.
/// </param>
/// <exception cref="MetadataException">
/// If a parameter set name has already been declared on this parameter.
/// </exception>
private void ProcessParameterAttribute(
string parameterName,
ParameterAttribute parameter)
{
// If the parameter set name already exists on this parameter and the set name is the default parameter
// set name, it is an error.
if (ParameterSetData.ContainsKey(parameter.ParameterSetName))
{
MetadataException e =
new MetadataException(
"ParameterDeclaredInParameterSetMultipleTimes",
null,
DiscoveryExceptions.ParameterDeclaredInParameterSetMultipleTimes,
parameterName,
parameter.ParameterSetName);
throw e;
}
if (parameter.ValueFromPipeline || parameter.ValueFromPipelineByPropertyName)
{
IsPipelineParameterInSomeParameterSet = true;
}
if (parameter.Mandatory)
{
IsMandatoryInSomeParameterSet = true;
}
// Construct an instance of the parameter set specific data
ParameterSetSpecificMetadata parameterSetSpecificData = new ParameterSetSpecificMetadata(parameter);
ParameterSetData.Add(parameter.ParameterSetName, parameterSetSpecificData);
}
public override string ToString()
{
return Name;
}
#endregion helper methods
}
/// <summary>
/// The types of collections that are supported as parameter types.
/// </summary>
internal enum ParameterCollectionType
{
NotCollection,
IList,
Array,
ICollectionGeneric
}
/// <summary>
/// Contains the collection type information for a parameter.
/// </summary>
internal class ParameterCollectionTypeInformation
{
/// <summary>
/// Constructs a parameter collection type information object
/// which exposes the specified Type's collection type in a
/// simple way.
/// </summary>
/// <param name="type">
/// The type to determine the collection information for.
/// </param>
internal ParameterCollectionTypeInformation(Type type)
{
ParameterCollectionType = ParameterCollectionType.NotCollection;
Diagnostics.Assert(type != null, "Caller to verify type argument");
// NTRAID#Windows OS Bugs-1009284-2004/05/11-JeffJon
// What other collection types should be supported?
// Look for array types
// NTRAID#Windows Out of Band Releases-906820-2005/09/07
// According to MSDN, IsSubclassOf returns false if the types are exactly equal.
// Should this include ==?
if (type.IsSubclassOf(typeof(Array)))
{
ParameterCollectionType = ParameterCollectionType.Array;
ElementType = type.GetElementType();
return;
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return;
}
Type[] interfaces = type.GetInterfaces();
if (interfaces.Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IDictionary<,>))
|| (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IDictionary<,>)))
{
return;
}
bool implementsIList = (type.GetInterface(nameof(IList)) != null);
// Look for class Collection<T>. Collection<T> implements IList, and also IList
// is more efficient to bind than ICollection<T>. This optimization
// retrieves the element type so that we can coerce the elements.
// Otherwise they must already be the right type.
if (implementsIList && type.IsGenericType && (type.GetGenericTypeDefinition() == typeof(Collection<>)))
{
ParameterCollectionType = ParameterCollectionType.IList;
// figure out elementType
Type[] elementTypes = type.GetGenericArguments();
Diagnostics.Assert(
elementTypes.Length == 1,
"Expected 1 generic argument, got " + elementTypes.Length);
ElementType = elementTypes[0];
return;
}
// Look for interface ICollection<T>. Note that Collection<T>
// does not implement ICollection<T>, and also, ICollection<T>
// does not derive from IList. The only way to add elements
// to an ICollection<T> is via reflected calls to Add(T),
// but the advantage over plain IList is that we can typecast the elements.
Type interfaceICollection =
Array.Find(interfaces, static i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(ICollection<>));
if (interfaceICollection != null)
{
// We only deal with the first type for which ICollection<T> is implemented
ParameterCollectionType = ParameterCollectionType.ICollectionGeneric;
// figure out elementType
Type[] elementTypes = interfaceICollection.GetGenericArguments();
Diagnostics.Assert(
elementTypes.Length == 1,
"Expected 1 generic argument, got " + elementTypes.Length);
ElementType = elementTypes[0];
return;
}
// Look for IList
if (implementsIList)
{
ParameterCollectionType = ParameterCollectionType.IList;
// elementType remains null
return;
}
}
/// <summary>
/// The collection type of the parameter.
/// </summary>
internal ParameterCollectionType ParameterCollectionType { get; }
/// <summary>
/// The type of the elements in the collection.
/// </summary>
internal Type ElementType { get; }
}
}
|