コード例 #1
0
        /// <summary>
        ///     Returns the value of this element, converted to type T. If the element does not exist returns the default
        ///     value. If the element's value cannot be converted, throws an exception.</summary>
        public static T ValueOrDefault <T>(this XElement element, XName name, T defaultValue)
        {
            XElement el = element.Element(name);

            if (el == null)
            {
                return(defaultValue);
            }
            else
            {
                try { return(ExactConvert.To <T>(el.Value)); }
                catch (ExactConvertException E) { throw new InvalidOperationException(("Element \"{0}/{1}\", when present, must contain a value convertible to a certain type: " + E.Message).Fmt(element.Path(), name)); }
            }
        }
コード例 #2
0
        public static T GetValidated <T>(this HttpRequest request, string varName, T varDefault, Func <T, bool> validator, string mustBe)
        {
            var valueStr = request.Url[varName];

            if (valueStr == null)
            {
                return(varDefault);
            }

            T value;

            try { value = ExactConvert.To <T>(valueStr); }
            catch (ExactConvertException) { throw new ValidationException(varName, valueStr, "convertible to {0}".Fmt(typeof(T))); }

            if (!validator(value))
            {
                throw new ValidationException(varName, valueStr, mustBe);
            }

            return(value);
        }