using DSInternals.Common; using System; using System.Management.Automation; using System.Security; namespace DSInternals.PowerShell { // TODO: Modify comments for ValidateSecureStringLengthAttribute. /// /// The ValidatePasswordLength attribute specifies the minimum and maximum number of characters for a cmdlet parameter argument. This attribute can also be used by Windows PowerShell functions. /// [AttributeUsageAttribute(AttributeTargets.Property | AttributeTargets.Field)] public sealed class ValidatePasswordLengthAttribute : ValidateEnumeratedArgumentsAttribute { /// /// Initializes a new instance of the ValidatePasswordLengthAttribute class with the minimum and maximum lengths for the cmdlet parameter arguments. /// /// Specifies the minimum number of characters allowed. /// Specifies the maximum number of characters allowed. public ValidatePasswordLengthAttribute(int minLength, int maxLength) { // Validate parameters: if (minLength < 0) { throw new ArgumentOutOfRangeException("minLength"); } if (maxLength <= 0) { throw new ArgumentOutOfRangeException("maxLength"); } if (maxLength < minLength) { // TODO: Extract message as a resource new ValidationMetadataException("Maximum length must be greater than or equal to the minimum length."); } // Set properties: this.MinLength = minLength; this.MaxLength = maxLength; } /// /// Gets the maximum number of characters (length) that is allowed for the cmdlet parameter argument. /// public int MaxLength { get; private set; } /// /// Gets the minimum number of characters (length) that is allowed for the cmdlet parameter argument. /// public int MinLength { get; private set; } /// /// Validates a specified argument value of an enumerated argument. /// /// The argument to be validated. protected override void ValidateElement(object password) { SecureString pwd = password as SecureString; Validator.AssertNotNull(pwd, "password"); int length = pwd.Length; if (length < this.MinLength || length > this.MaxLength) { // TODO: Extract as resource string message = String.Format("The password must be {0}-{1} characters long.", this.MinLength, this.MaxLength); throw new ValidationMetadataException(message); } } } }