Ejemplo n.º 1
0
        /// <summary>
        /// Changes the type (with extended handling for booleans and empty strings).
        /// </summary>
        /// <param name="value">The value.</param>
        /// <param name="tgtType">Type of the TGT.</param>
        /// <param name="culture">The culture.</param>
        /// <returns></returns>
        public static object ChangeTypeExtended(object value, Type tgtType, CultureInfo culture = null)
        {
            if (tgtType == null)
            {
                return(value);
            }

            object tgtValue = null;

            if ((tgtType == typeof(bool) || tgtType == typeof(bool?)) && value is string)
            {
                // Special handling for Boolean
                string strValue = (value as string).Trim().ToLower();
                if (strValue == "1" || strValue == "true" || strValue == "yes" || strValue == "y")
                {
                    tgtValue = true;
                }
                else
                {
                    tgtValue = false;
                }
            }
            else if (tgtType != typeof(string) && string.IsNullOrWhiteSpace(value.ToStringOrEmpty()))
            {
                // special handling for whitespace strings, for non string types
                tgtValue = Activator.CreateInstance(tgtType);
            }
            else
            {
                tgtValue = ConvertExtensions.ChangeType(value, tgtType, culture);
            }

            return(tgtValue);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Gets the attribute value.
        /// </summary>
        /// <param name="element">The element.</param>
        /// <param name="name">The name.</param>
        /// <param name="defaultValue">The default Value.</param>
        /// <returns></returns>
        public static T GetAttributeValue <T>(this XElement element, string name, T defaultValue = default(T))
        {
            XAttribute attribute = element.Attribute(XName.Get(name));

            if (attribute == null)
            {
                return(defaultValue);
            }

            return(ConvertExtensions.ConvertTo <T>(attribute.Value));
        }