static private bool ValidateScopeSpecifier(string specifier, bool numberAllowed) { int scopeLevel = -1; //first try to interprete it as an int. if we don't do this, the enums TryParse method will misinterpret it if (int.TryParse(specifier, out scopeLevel) && (scopeLevel < 0 || !numberAllowed)) { return(false); } ScopeSpecifiers scopeSpecifier; if (!ScopeSpecifiers.TryParse(specifier, true, out scopeSpecifier)) { return(false); } return(true); }
private SessionStateScope <T> GetScope(string specifier, bool numberAllowed, SessionStateScope <T> fallback = null) { int scopeLevel = -1; if (String.IsNullOrEmpty(specifier)) { return(fallback); } SessionStateScope <T> candidate = this; //check if the specifier is a number before trying to interprete it as enum if (int.TryParse(specifier, out scopeLevel)) { //sometimes a number specifies the relative scope location, but in some contexts this isn't allowed //this has to happen *after* trying to parse them as e.g. "0" would be a parsable enum value! if (!numberAllowed || scopeLevel < 0) { throw new ArgumentException("Invalid scope specifier"); } for (var curLevel = scopeLevel; curLevel > 0; curLevel--) { //make sure we can proceed looking for the next scope candidate = candidate.ParentScope; if (candidate == null) { throw new ArgumentOutOfRangeException("Exceeded the maximum number of available scopes"); } } return(candidate); } //it's not a (positive) number, let's check if it's a named scope ScopeSpecifiers scopeSpecifier; if (!ScopeSpecifiers.TryParse(specifier, true, out scopeSpecifier)) { throw new ArgumentException(String.Format("Invalid scope specifier \"{0}\".", specifier)); } return(GetScope(scopeSpecifier)); }