Skip to content

Instantly share code, notes, and snippets.

@IISResetMe
Forked from endowdly/ValidateScopeAttribute.cs
Created February 16, 2019 21:15
Show Gist options
  • Save IISResetMe/6cd60c27f1f3d383abd4c7893c034b23 to your computer and use it in GitHub Desktop.
Save IISResetMe/6cd60c27f1f3d383abd4c7893c034b23 to your computer and use it in GitHub Desktop.
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Management.Automation.Internal;
using System.Management.Automation.Language;
using System.Runtime.CompilerServices;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace System.Management.Automation.Internal
{
[AttributeUsage (AttributeTargets.Field | AttributeTargets.Property)]
public sealed class ValidateScopeAttribute : ValidateEnumeratedArgumentsAttribute
{
// We will use static values here like "Global", "Locale", etc.
private const string[] scopes = { "Private", "Local", "Script", "Global" };
public string ErrorMessage { get; set; }
// I should just hardcode this to true. Useful for sets, not so much for defined scopes.
public bool IgnoreCase { get; set; } = true;
private string[] _validValues;
public IList<string> ValidValues
{
get
{
if (_validValues == null) return scopes;
return _validValues;
}
}
protected override void ValidateElement (object element)
{
if (ValidValues.NotContains (element))
{
throw new Expection
}
if (element == null)
{
throw new ValidationMetadataException (
"ArgumentIsEmpty",
null,
Metadata.ValidateNotNullFailure);
}
string objString = element.ToString ();
foreach (string setString in ValidValues)
{
// The complex `if` in ValidateSetAttribute is insane. Not hard to read or understand, but insane.
var objIsValid = CultureInfo.InvariantCulture.CompareInfo.Compare (
setString,
objString,
IgnoreCase
? CompareOptions.IgnoreCase
: CompareOptions.None
);
if (objIsValid == 0)
{
return;
}
else
{
// So the named scopes failed. We should check to see if we have a number scope.
// This doesn't seem _super_ robust, and how far should we go in scope?
if (int.TryParse (objString, null)) return;
}
}
// Todo: Add ValidateScope MetaStuff
// -- Done: 2018-11-16T08:52:35.8504659-05:00
// -- Action: Edit .../System.Management.Automation/resources/Metadata.resx
var errorMessageFormat = String.IsNullOrEmpty (ErrorMessage)
? Metadata.ValidateScopeFailure
: ErrorMessage
throw new ValidationMetadataException (
"ValidateScopeFailure",
null,
element.ToString (),
SetAsString ()
);
}
private string SetAsString ()
{
return string.Join (CultureInfo.CurrentUICulture.TextInfo.ListSeperator, ValidValues);
}
public ValidatateScopeAttribute (params string[] validValues)
{
// We check for null in the class so this can be null
_validValues = validValues
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment