Пример #1
0
        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            string s = value as string;

            if (s == null)
            {
                return(base.ConvertFrom(context, culture, value));
            }

            if (culture == null)
            {
                culture = CultureInfo.CurrentCulture;
            }
            string[] subs = s.Split(culture.TextInfo.ListSeparator.ToCharArray());

            SingleConverter converter = new SingleConverter();

            float[] numSubs = new float[subs.Length];
            for (int i = 0; i < numSubs.Length; i++)
            {
                numSubs[i] = (float)converter.ConvertFromString(context, culture, subs[i]);
            }

            if (subs.Length != 2)
            {
                throw new ArgumentException("Failed to parse Text(" + s + ") expected text in the format \"Width,Height.\"");
            }

            return(new SizeF(numSubs[0], numSubs[1]));
        }
Пример #2
0
        public void PropertiesTest()
        {
            var converter = new SingleConverter();

            Assert.AreEqual(true, converter.AcceptsNativeType);
            Assert.AreEqual(typeof(float), converter.ConvertedType);
        }
Пример #3
0
        /// <summary>Converts the given object to the type of this converter, using the specified context and culture information.</summary>
        /// <param name="context">An <see cref="T:System.ComponentModel.ITypeDescriptorContext" /> that provides a format context. </param>
        /// <param name="culture">The <see cref="T:System.Globalization.CultureInfo" /> to use as the current culture. </param>
        /// <param name="value">The <see cref="T:System.Object" /> to convert. </param>
        /// <returns>An <see cref="T:System.Object" /> that represents the converted value.</returns>
        // Token: 0x060007E2 RID: 2018 RVA: 0x00012420 File Offset: 0x00010620
        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            string text = value as string;

            if (text == null)
            {
                return(base.ConvertFrom(context, culture, value));
            }
            if (culture == null)
            {
                culture = CultureInfo.CurrentCulture;
            }
            string[]        array           = text.Split(culture.TextInfo.ListSeparator.ToCharArray());
            SingleConverter singleConverter = new SingleConverter();

            float[] array2 = new float[array.Length];
            for (int i = 0; i < array2.Length; i++)
            {
                array2[i] = (float)singleConverter.ConvertFromString(context, culture, array[i]);
            }
            if (array.Length != 2)
            {
                throw new ArgumentException("Failed to parse Text(" + text + ") expected text in the format \"Width,Height.\"");
            }
            return(new SizeF(array2[0], array2[1]));
        }
Пример #4
0
        /// <summary>
        /// Convert a field to a string
        /// </summary>
        /// <param name="o">object we want to convert</param>
        /// <returns>string representation of the string</returns>
        internal string ValueToString(object o)
        {
            if (mDecimalConv == null)
            {
                mDecimalConv = new DecimalConverter(DecimalSeparator);
                mDoubleConv  = new DoubleConverter(DecimalSeparator);
                mSingleConv  = new SingleConverter(DecimalSeparator);
                mDateConv    = new DateTimeConverter(DateFormat);
            }

            if (o == null)
            {
                return(string.Empty);
            }
            else if (o is DateTime)
            {
                return(mDateConv.FieldToString(o));
            }
            else if (o is decimal)
            {
                return(mDecimalConv.FieldToString(o));
            }
            else if (o is double)
            {
                return(mDoubleConv.FieldToString(o));
            }
            else if (o is float)
            {
                return(mSingleConv.FieldToString(o));
            }
            else
            {
                return(o.ToString());
            }
        }
Пример #5
0
 static Converter()
 {
     BoolConverter.Initialize();
     CharConverter.Initialize();
     ByteConverter.Initialize();
     SByteConverter.Initialize();
     Int16Converter.Initialize();
     UInt16Converter.Initialize();
     Int32Converter.Initialize();
     UInt32Converter.Initialize();
     Int64Converter.Initialize();
     UInt64Converter.Initialize();
     SingleConverter.Initialize();
     DoubleConverter.Initialize();
     DecimalConverter.Initialize();
     BigIntegerConverter.Initialize();
     BytesConverter.Initialize();
     CharsConverter.Initialize();
     StringConverter.Initialize();
     StringBuilderConverter.Initialize();
     DateTimeConverter.Initialize();
     TimeSpanConverter.Initialize();
     GuidConverter.Initialize();
     MemoryStreamConverter.Initialize();
     StreamConverter.Initialize();
 }
Пример #6
0
        private Font(SerializationInfo info, StreamingContext context)
        {
            string                      familyName      = null;
            float                       emSize          = -1f;
            FontStyle                   style           = FontStyle.Regular;
            GraphicsUnit                unit            = GraphicsUnit.Point;
            SingleConverter             singleConverter = new SingleConverter();
            SerializationInfoEnumerator enumerator      = info.GetEnumerator();

            while (enumerator.MoveNext())
            {
                if (string.Equals(enumerator.Name, "Name", StringComparison.OrdinalIgnoreCase))
                {
                    familyName = (string)enumerator.Value;
                }
                else if (string.Equals(enumerator.Name, "Size", StringComparison.OrdinalIgnoreCase))
                {
                    emSize = ((!(enumerator.Value is string)) ? ((float)enumerator.Value) : ((float)singleConverter.ConvertFrom(enumerator.Value)));
                }
                else if (string.Compare(enumerator.Name, "Style", ignoreCase: true, CultureInfo.InvariantCulture) == 0)
                {
                    style = (FontStyle)enumerator.Value;
                }
                else if (string.Compare(enumerator.Name, "Unit", ignoreCase: true, CultureInfo.InvariantCulture) == 0)
                {
                    unit = (GraphicsUnit)enumerator.Value;
                }
            }
            Initialize(familyName, emSize, style, unit, 1, IsVerticalName(familyName));
        }
    internal Unit(string value, CultureInfo culture, UnitType defaultType)
    {
        if (string.IsNullOrEmpty(value))
        {
            this.@value = 0;
            this.type   = (UnitType)0;
            return;
        }
        if (culture == null)
        {
            culture = CultureInfo.CurrentCulture;
        }
        string lower  = value.Trim().ToLower(CultureInfo.InvariantCulture);
        int    length = lower.Length;
        int    num    = -1;

        for (int i = 0; i < length; i++)
        {
            char chr = lower[i];
            if ((chr < '0' || chr > '9') && chr != '-' && chr != '.' && chr != ',')
            {
                break;
            }
            num = i;
        }
        if (num == -1)
        {
            object[] objArray = new object[] { value };
            throw new FormatException(SR.GetString("UnitParseNoDigits", objArray));
        }
        if (num >= length - 1)
        {
            this.type = defaultType;
        }
        else
        {
            this.type = Unit.GetTypeFromString(lower.Substring(num + 1).Trim());
        }
        string str = lower.Substring(0, num + 1);

        try
        {
            TypeConverter singleConverter = new SingleConverter();
            this.@value = (double)((float)singleConverter.ConvertFromString(null, culture, str));
            if (this.type == UnitType.Pixel)
            {
                this.@value = (double)((int)this.@value);
            }
        }
        catch
        {
            object[] objArray1 = new object[] { value, str, this.type.ToString("G") };
            throw new FormatException(SR.GetString("UnitParseNumericPart", objArray1));
        }
        if (this.@value < -32768 || this.@value > 32767)
        {
            throw new ArgumentOutOfRangeException("value");
        }
    }
Пример #8
0
        public void RoundTripMinValueTest()
        {
            var converter = new SingleConverter();
            var s         = converter.ConvertToString(float.MinValue, null, new MemberMapData(null));
            var f         = converter.ConvertFromString(s, null, new MemberMapData(null));

            Assert.Equal(float.MinValue, f);
        }
Пример #9
0
        /// <summary>
        /// Extends ConvertTo so that methods that return a specific type object given a Type parameter can be
        /// used as generic method and casting is not required.
        /// <example>
        /// basenumberconverter.ConvertTo<int>(context, culture, value);
        /// </example>
        /// </summary>
        public static T ConvertTo <T>(this SingleConverter basenumberconverter, ITypeDescriptorContext context, System.Globalization.CultureInfo culture, Object value)
        {
            if (basenumberconverter == null)
            {
                throw new ArgumentNullException("basenumberconverter");
            }

            return((T)basenumberconverter.ConvertTo(context, culture, value, typeof(T)));
        }
Пример #10
0
        /// <summary>
        /// Extends ConvertTo so that methods that return a specific type object given a Type parameter can be
        /// used as generic method and casting is not required.
        /// <example>
        /// typeconverter.ConvertTo<int>(value);
        /// </example>
        /// </summary>
        public static T ConvertTo <T>(this SingleConverter typeconverter, Object value)
        {
            if (typeconverter == null)
            {
                throw new ArgumentNullException("typeconverter");
            }

            return((T)typeconverter.ConvertTo(value, typeof(T)));
        }
Пример #11
0
 internal Unit(string value, CultureInfo culture, UnitType defaultType)
 {
     if (string.IsNullOrEmpty(value))
     {
         this.value = 0.0;
         this.type  = (UnitType)0;
     }
     else
     {
         if (culture == null)
         {
             culture = CultureInfo.CurrentCulture;
         }
         string str    = value.Trim().ToLower(CultureInfo.InvariantCulture);
         int    length = str.Length;
         int    num2   = -1;
         for (int i = 0; i < length; i++)
         {
             char ch = str[i];
             if (((ch < '0') || (ch > '9')) && (((ch != '-') && (ch != '.')) && (ch != ',')))
             {
                 break;
             }
             num2 = i;
         }
         if (num2 == -1)
         {
             throw new FormatException(System.Web.SR.GetString("UnitParseNoDigits", new object[] { value }));
         }
         if (num2 < (length - 1))
         {
             this.type = GetTypeFromString(str.Substring(num2 + 1).Trim());
         }
         else
         {
             this.type = defaultType;
         }
         string text = str.Substring(0, num2 + 1);
         try
         {
             TypeConverter converter = new SingleConverter();
             this.value = (float)converter.ConvertFromString(null, culture, text);
             if (this.type == UnitType.Pixel)
             {
                 this.value = (int)this.value;
             }
         }
         catch
         {
             throw new FormatException(System.Web.SR.GetString("UnitParseNumericPart", new object[] { value, text, this.type.ToString("G") }));
         }
         if ((this.value < -32768.0) || (this.value > 32767.0))
         {
             throw new ArgumentOutOfRangeException("value");
         }
     }
 }
Пример #12
0
        private void Init(string value, CultureInfo culture, RVUnitType defaultType)
        {
            if (culture == null)
            {
                culture = CultureInfo.CurrentCulture;
            }
            string text   = value.Trim().ToLower(culture);
            int    length = text.Length;
            int    num    = -1;

            for (int i = 0; i < length; i++)
            {
                char c = text[i];
                if ((c < '0' || c > '9') && c != '-' && c != '.' && c != ',')
                {
                    break;
                }
                num = i;
            }
            if (num == -1)
            {
                throw new FormatException();
            }
            if (num < length - 1)
            {
                m_type = GetTypeFromString(text.Substring(num + 1).Trim());
            }
            else
            {
                if (defaultType == (RVUnitType)0)
                {
                    throw new FormatException();
                }
                m_type = defaultType;
            }
            string text2 = text.Substring(0, num + 1);

            try
            {
                TypeConverter typeConverter = new SingleConverter();
                m_value = (float)typeConverter.ConvertFromString(null, culture, text2);
            }
            catch (Exception ex)
            {
                Exception ex2 = FindStoppingException(ex);
                if (ex2 == ex)
                {
                    throw;
                }
                if (ex2 != null)
                {
                    throw ex2;
                }
                throw new FormatException();
            }
        }
Пример #13
0
        public void TargetType()
        {
            // Arrange
            IConverter converter    = new SingleConverter();
            var        expectedType = typeof(Single);

            // Act
            var actualType = converter.TargetType;

            // Assert
            Assert.Equal(expectedType, actualType);
        }
Пример #14
0
        private void Init(string value, CultureInfo culture, UnitType defaultType)
        {
            if (culture == null)
            {
                culture = CultureInfo.CurrentCulture;
            }

            string valueString = value.Trim().ToLower();
            int    valueLength = valueString.Length;
            int    num2        = -1;

            for (int i = 0; i < valueLength; i++)
            {
                char currentChar = valueString[i];
                if (((currentChar < '0') || (currentChar > '9')) && (((currentChar != '-') && (currentChar != '.')) && (currentChar != ',')))
                {
                    break;
                }

                num2 = i;
            }
            if (num2 == -1)
            {
                throw new FormatException(string.Format("{0} cannot be parsed as a unit because it does not contain numeric values. Examples of valid unit strings are \"1pt\" and \".5in\".", value));
            }

            if (num2 < (valueLength - 1))
            {
                _type = Unit.GetTypeFromString(valueString.Substring(num2 + 1).Trim());
            }
            else
            {
                if (defaultType == ((UnitType)0))
                {
                    throw new FormatException(string.Format("{0} does not contain a unit specification. Examples of valid unit strings are \"1pt\" and \".5in\".", value));
                }

                _type = defaultType;
            }

            string valueSubstring = valueString.Substring(0, num2 + 1);

            try
            {
                TypeConverter converter = new SingleConverter();
                _value = (float)converter.ConvertFromString(null, CultureInfo.InvariantCulture, valueSubstring);
            }
            catch
            {
                throw new FormatException(string.Format("The numeric portion of {0} cannot be parsed as a unit of type {1}.", value, _type.ToString("G")));
            }
        }
Пример #15
0
        private JsonFxAOT()
        {
            TypeConverter c;

            c          = new ArrayConverter();
            m_fakeFlag = c.Equals(c);
            //c = new BaseNumberConverter();
            //m_fakeFlag = c.Equals(c);
            c          = new BooleanConverter();
            m_fakeFlag = c.Equals(c);
            c          = new ByteConverter();
            m_fakeFlag = c.Equals(c);
            c          = new CollectionConverter();
            m_fakeFlag = c.Equals(c);
            c          = new ComponentConverter(typeof(int));
            m_fakeFlag = c.Equals(c);
            c          = new CultureInfoConverter();
            m_fakeFlag = c.Equals(c);
            c          = new DateTimeConverter();
            m_fakeFlag = c.Equals(c);
            c          = new DecimalConverter();
            m_fakeFlag = c.Equals(c);
            c          = new DoubleConverter();
            m_fakeFlag = c.Equals(c);
            c          = new EnumConverter(typeof(int));
            m_fakeFlag = c.Equals(c);
            c          = new ExpandableObjectConverter();
            m_fakeFlag = c.Equals(c);
            c          = new Int16Converter();
            m_fakeFlag = c.Equals(c);
            c          = new Int32Converter();
            m_fakeFlag = c.Equals(c);
            c          = new Int64Converter();
            m_fakeFlag = c.Equals(c);
            c          = new NullableConverter(typeof(object));
            m_fakeFlag = c.Equals(c);
            c          = new SByteConverter();
            m_fakeFlag = c.Equals(c);
            c          = new SingleConverter();
            m_fakeFlag = c.Equals(c);
            c          = new StringConverter();
            m_fakeFlag = c.Equals(c);
            c          = new TimeSpanConverter();
            m_fakeFlag = c.Equals(c);
            c          = new UInt16Converter();
            m_fakeFlag = c.Equals(c);
            c          = new UInt32Converter();
            m_fakeFlag = c.Equals(c);
            c          = new UInt64Converter();
            m_fakeFlag = c.Equals(c);
        }
Пример #16
0
        /// <summary>
        /// Tries to parse a 32-bit single precision float from a string. This method should handle hexadecimal values
        /// as well as normal values.
        /// </summary>
        /// <param name="value">The string value to parse.</param>
        /// <param name="result">The parsed float value, if the string was valid. If invalid, this
        /// will be the default float value value.</param>
        /// <returns>True if the conversion was successful; otherwise returns false.</returns>
        public static bool TryParseEx(string value, out float result)
        {
            bool canConvert = true;

            try
            {
                var converter = new SingleConverter();
                result = (float)converter.ConvertFromString(value);
            }
            catch (Exception)
            {
                result     = default(float);
                canConvert = false;
            }

            return(canConvert);
        }
Пример #17
0
Файл: Font.cs Проект: ash2005/z
        private Font(SerializationInfo info, StreamingContext context)
        {
            Debug.Assert(info != null, "Didn't expect a null parameter");

            string          name  = null;
            float           size  = -1f;
            FontStyle       style = FontStyle.Regular;
            GraphicsUnit    unit  = GraphicsUnit.Point;
            SingleConverter sc    = new SingleConverter();

            SerializationInfoEnumerator sie = info.GetEnumerator();

            for (; sie.MoveNext();)
            {
                if (String.Equals(sie.Name, "Name", StringComparison.OrdinalIgnoreCase))
                {
                    name = (string)sie.Value;
                }
                else if (String.Equals(sie.Name, "Size", StringComparison.OrdinalIgnoreCase))
                {
                    if (sie.Value is System.String)
                    {
                        size = (float)sc.ConvertFrom(sie.Value);
                    }
                    else
                    {
                        size = (float)sie.Value;
                    }
                }
                else if (String.Compare(sie.Name, "Style", true, CultureInfo.InvariantCulture) == 0)
                {
                    style = (FontStyle)sie.Value;
                }
                else if (String.Compare(sie.Name, "Unit", true, CultureInfo.InvariantCulture) == 0)
                {
                    unit = (GraphicsUnit)sie.Value;
                }
                else
                {
                    Debug.Fail("Unknown serialization item for font: " + sie.Name);
                }
            }

            Initialize(name, size, style, unit, SafeNativeMethods.DEFAULT_CHARSET, IsVerticalName(name));
        }
Пример #18
0
        public void Conversion()
        {
            // Arrange
            IConverter converter     = new SingleConverter();
            var        value         = "42,1";
            var        expectedValue = (Single)42.1;

            // Act
            using (new LangageSwitcher("fr-fr"))
            {
                var actualValue = converter.Convert(value, converter.TargetType);

                // Assert
                Assert.NotNull(actualValue);
                Assert.IsType <Single>(actualValue);
                Assert.Equal(expectedValue, (Single)actualValue);
            }
        }
Пример #19
0
        public void ConvertFromExcelTest()
        {
            var converter            = new SingleConverter();
            var typeConverterOptions = new TypeConverterOptions {
                CultureInfo = CultureInfo.CurrentCulture
            };

            Assert.AreEqual((float)12.3, converter.ConvertFromExcel(typeConverterOptions, 12.3));
            Assert.AreEqual((float)12.3, converter.ConvertFromExcel(typeConverterOptions, "12.3"));
            Assert.AreEqual((float)12.3, converter.ConvertFromExcel(typeConverterOptions, " 12.3 "));
            Assert.AreEqual((float)0, converter.ConvertFromExcel(typeConverterOptions, null));

            try {
                converter.ConvertFromExcel(typeConverterOptions, "");
                Assert.Fail();
            } catch (ExcelTypeConverterException) {
            }
        }
Пример #20
0
        private Font(SerializationInfo info, StreamingContext context)
        {
            string                      familyName      = null;
            float                       emSize          = -1f;
            FontStyle                   style           = FontStyle.Regular;
            GraphicsUnit                unit            = GraphicsUnit.Point;
            SingleConverter             singleConverter = new SingleConverter();
            SerializationInfoEnumerator enumerator      = info.GetEnumerator();

            while (enumerator.MoveNext())
            {
                if (string.Equals(enumerator.Name, "Name", StringComparison.OrdinalIgnoreCase))
                {
                    familyName = (string)enumerator.Value;
                }
                else if (string.Equals(enumerator.Name, "Size", StringComparison.OrdinalIgnoreCase))
                {
                    emSize = ((!(enumerator.Value is string))
                        ? ((float)enumerator.Value)
                        : ((float)singleConverter.ConvertFrom(enumerator.Value)));
                }
                else if (string.Compare(enumerator.Name, "Style", ignoreCase: true, CultureInfo.InvariantCulture) == 0)
                {
                    style = (FontStyle)enumerator.Value;
                }
                else if (string.Compare(enumerator.Name, "Unit", ignoreCase: true, CultureInfo.InvariantCulture) == 0)
                {
                    unit = (GraphicsUnit)enumerator.Value;
                }
            }

            //Initialize(familyName, emSize, style, unit, 1, IsVerticalName(familyName));
            if (unit == GraphicsUnit.Point)
            {
                emSize *= 1.333f;
            }

            nativeFont = new SKPaint()
            {
                Typeface     = SKTypeface.Default, TextSize = emSize, Style = SKPaintStyle.Fill,
                TextAlign    = SKTextAlign.Left, IsVerticalText = IsVerticalName(familyName),
                TextEncoding = SKTextEncoding.Utf8
            };
        }
Пример #21
0
        private Font(SerializationInfo info, StreamingContext context)
        {
            this.gdiCharSet     = 1;
            this.systemFontName = "";
            string                      familyName = null;
            float                       emSize     = -1f;
            FontStyle                   regular    = FontStyle.Regular;
            GraphicsUnit                point      = GraphicsUnit.Point;
            SingleConverter             converter  = new SingleConverter();
            SerializationInfoEnumerator enumerator = info.GetEnumerator();

            while (enumerator.MoveNext())
            {
                if (string.Equals(enumerator.Name, "Name", StringComparison.OrdinalIgnoreCase))
                {
                    familyName = (string)enumerator.Value;
                }
                else
                {
                    if (string.Equals(enumerator.Name, "Size", StringComparison.OrdinalIgnoreCase))
                    {
                        if (enumerator.Value is string)
                        {
                            emSize = (float)converter.ConvertFrom(enumerator.Value);
                        }
                        else
                        {
                            emSize = (float)enumerator.Value;
                        }
                        continue;
                    }
                    if (string.Compare(enumerator.Name, "Style", true, CultureInfo.InvariantCulture) == 0)
                    {
                        regular = (FontStyle)enumerator.Value;
                    }
                    else if (string.Compare(enumerator.Name, "Unit", true, CultureInfo.InvariantCulture) == 0)
                    {
                        point = (GraphicsUnit)enumerator.Value;
                    }
                }
            }
            this.Initialize(familyName, emSize, regular, point, 1, IsVerticalName(familyName));
        }
Пример #22
0
        /// <summary>
        /// Converts the specified value to a <see cref="SizeF"/>
        /// </summary>
        /// <param name="context">Conversion context</param>
        /// <param name="culture">Culture to perform the conversion</param>
        /// <param name="value">Value to convert</param>
        /// <returns>A new instance of a <see cref="SizeF"/> converted from the specified <paramref name="value"/></returns>
        public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
        {
            var text = value as string;

            if (text != null)
            {
                var parts = text.Split(culture.TextInfo.ListSeparator.ToCharArray());
                if (parts.Length != 2)
                {
                    throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Cannot parse value '{0}' as size. Should be in the form of 'width,height'", text));
                }

                var converter = new SingleConverter();
                return(new SizeF(
                           (float)converter.ConvertFromString(context, culture, parts [0]),
                           (float)converter.ConvertFromString(context, culture, parts [1])
                           ));
            }
            return(base.ConvertFrom(context, culture, value));
        }
Пример #23
0
        public void BadValueConversion()
        {
            // Arrange
            IConverter converter = new SingleConverter();
            var        value     = "Hello";
            var        expectedExceptionMessage      = Constants.ExceptionMessages.FormatConverterUnableConvert(value, typeof(float));
            var        expectedInnerExceptionMessage = "Input string was not in a correct format.";

            // Act
            using (new LangageSwitcher("en-us"))
            {
                var actualException = Assert.Throws <CommandLineParserException>(() => converter.Convert(value, converter.TargetType));

                // Assert
                Assert.Equal(expectedExceptionMessage, actualException.Message);
                Assert.NotNull(actualException.InnerException);
                var actualInnerExecption = Assert.IsAssignableFrom <FormatException>(actualException.InnerException);
                Assert.Equal(expectedInnerExceptionMessage, actualInnerExecption.Message);
            }
        }
Пример #24
0
 internal void Write(float value)
 {
     Write(SingleConverter.SingleToInt32Bits(value));
 }
Пример #25
0
 public void SetUp()
 {
     converter = new SingleConverter();
 }
        internal object ConvertToType(Type type, object obj)
        {
            if (obj == null)
            {
                return(null);
            }

            if (obj is IDictionary <string, object> )
            {
                if (type == null)
                {
                    obj = EvaluateDictionary((IDictionary <string, object>)obj);
                }
                else
                {
                    JavaScriptConverter converter = GetConverter(type);
                    if (converter != null)
                    {
                        return(converter.Deserialize(
                                   EvaluateDictionary((IDictionary <string, object>)obj),
                                   type, this));
                    }
                }

                return(ConvertToObject((IDictionary <string, object>)obj, type));
            }
            if (obj is IEnumerable <object> )
            {
                return(ConvertToList((IEnumerable <object>)obj, type));
            }

            if (type == null)
            {
                return(obj);
            }

            Type sourceType = obj.GetType();

            if (type.IsAssignableFrom(sourceType))
            {
                return(obj);
            }

            if (type.IsEnum)
            {
                return(Enum.ToObject(type, obj));
            }

            TypeConverter c = null;

            try {
                c = TypeDescriptor.GetConverter(type);
            } catch (Exception) {
                if (type.FullName == "System.Int32")
                {
                    c = new Int32Converter();
                    // int
                }
                else if (type.FullName == "System.Int64")
                {
                    c = new Int64Converter();
                    // long
                }
                else if (type.FullName == "System.Single")
                {
                    c = new SingleConverter();
                    // float
                }
                else if (type.FullName == "System.Double")
                {
                    c = new DoubleConverter();
                    // float
                }
                else if (type.FullName == "System.Boolean")
                {
                    c = new BooleanConverter();
                    // bool
                }
                else if (type.FullName == "System.Byte")
                {
                    c = new ByteConverter();
                }
            }

            if (c.CanConvertFrom(sourceType))
            {
                if (obj is string)
                {
                    return(c.ConvertFromInvariantString((string)obj));
                }

                return(c.ConvertFrom(obj));
            }

            /*
             * Take care of the special case whereas in JSON an empty string ("") really means
             * an empty value
             * (see: https://bugzilla.novell.com/show_bug.cgi?id=328836)
             */
            if ((type.IsGenericType) && (type.GetGenericTypeDefinition() == typeof(Nullable <>)))
            {
                string s = obj as String;
                if (String.IsNullOrEmpty(s))
                {
                    return(null);
                }
            }

            return(Convert.ChangeType(obj, type));
        }
Пример #27
0
        internal Unit(string value, CultureInfo culture, UnitType defaultType)
        {
            if (string.IsNullOrEmpty(value))
            {
                _value = 0.0f;
                _type  = (UnitType)0;
            }
            else
            {
                if (culture == null)
                {
                    culture = CultureInfo.CurrentCulture;
                }

                string str    = value.Trim().ToLower(CultureInfo.InvariantCulture);
                int    length = str.Length;
                int    num2   = -1;
                for (int i = 0; i < length; i++)
                {
                    char ch = str[i];
                    if (((ch < '0') || (ch > '9')) && (((ch != '-') && (ch != '.')) && (ch != ',')))
                    {
                        break;
                    }
                    num2 = i;
                }
                if (num2 == -1)
                {
                    throw new FormatException(string.Format("'{0}' cannot be parsed as a unit as there are no numeric values in it. Examples of valid unit strings are '30px' and '50%'.", value));
                }

                if (num2 < (length - 1))
                {
                    _type = GetTypeFromString(str.Substring(num2 + 1).Trim());
                }
                else
                {
                    _type = defaultType;
                }

                string text = str.Substring(0, num2 + 1);
                try
                {
                    TypeConverter converter = new SingleConverter();
                    _value = (float)converter.ConvertFromString(null, culture, text);
                    if (_type == UnitType.Pixel)
                    {
                        _value = (int)_value;
                    }
                }
                catch
                {
                    throw new FormatException(string.Format("The numeric part ('{1}') of '{0}' cannot be parsed as a numeric part of a {2} unit.", value, text, _type.ToString("G")));
                }

                if ((_value < -32768.0) || (_value > 32767.0))
                {
                    throw new ArgumentOutOfRangeException("value");
                }
            }
        }
Пример #28
0
        internal static TypeConverter GetCoreConverterFromCustomType(Type type)
        {
            TypeConverter result = null;

            if (type.IsEnum)
            {
                result = new EnumConverter(type);
            }
            else if (typeof(int).IsAssignableFrom(type))
            {
                result = new Int32Converter();
            }
            else if (typeof(short).IsAssignableFrom(type))
            {
                result = new Int16Converter();
            }
            else if (typeof(long).IsAssignableFrom(type))
            {
                result = new Int64Converter();
            }
            else if (typeof(uint).IsAssignableFrom(type))
            {
                result = new UInt32Converter();
            }
            else if (typeof(ushort).IsAssignableFrom(type))
            {
                result = new UInt16Converter();
            }
            else if (typeof(ulong).IsAssignableFrom(type))
            {
                result = new UInt64Converter();
            }
            else if (typeof(bool).IsAssignableFrom(type))
            {
                result = new BooleanConverter();
            }
            else if (typeof(double).IsAssignableFrom(type))
            {
                result = new DoubleConverter();
            }
            else if (typeof(float).IsAssignableFrom(type))
            {
                result = new SingleConverter();
            }
            else if (typeof(byte).IsAssignableFrom(type))
            {
                result = new ByteConverter();
            }
            else if (typeof(sbyte).IsAssignableFrom(type))
            {
                result = new SByteConverter();
            }
            else if (typeof(char).IsAssignableFrom(type))
            {
                result = new CharConverter();
            }
            else if (typeof(decimal).IsAssignableFrom(type))
            {
                result = new DecimalConverter();
            }
            else if (typeof(TimeSpan).IsAssignableFrom(type))
            {
                result = new TimeSpanConverter();
            }
            else if (typeof(Guid).IsAssignableFrom(type))
            {
                result = new GuidConverter();
            }
            else if (typeof(string).IsAssignableFrom(type))
            {
                result = new StringConverter();
            }
            else if (typeof(CultureInfo).IsAssignableFrom(type))
            {
                result = new CultureInfoConverter();
            }
            else if (typeof(Type).IsAssignableFrom(type))
            {
                result = new TypeTypeConverter();
            }
            else if (typeof(DateTime).IsAssignableFrom(type))
            {
                result = new DateTimeConverter2();
            }
            return(result);
        }
Пример #29
0
        internal Unit(string value, CultureInfo culture, UnitType defaultType)
        {
            if ((value == null) || (value.Length == 0))
            {
                this.value = 0;
                this.type  = (UnitType)0;
            }
            else
            {
                if (culture == null)
                {
                    culture = CultureInfo.CurrentCulture;
                }

                // This is invariant because it acts like an enum with a number together.
                // The enum part is invariant, but the number uses current culture.
                string trimLcase = value.Trim().ToLower(CultureInfo.InvariantCulture);
                int    len       = trimLcase.Length;

                int lastDigit = -1;
                for (int i = 0; i < len; i++)
                {
                    char ch = trimLcase[i];
                    if (((ch < '0') || (ch > '9')) && (ch != '-') && (ch != '.') && (ch != ','))
                    {
                        break;
                    }
                    lastDigit = i;
                }
                if (lastDigit == -1)
                {
                    throw new FormatException(SR.GetString(SR.UnitParseNoDigits, value));
                }
                if (lastDigit < len - 1)
                {
                    type = (UnitType)GetTypeFromString(trimLcase.Substring(lastDigit + 1).Trim());
                }
                else
                {
                    type = defaultType;
                }

                string numericPart = trimLcase.Substring(0, lastDigit + 1);
                // Cannot use Double.FromString, because we don't use it in the ToString implementation
                try {
                    if (type == UnitType.Pixel)
                    {
                        TypeConverter converter = new Int32Converter();
                        this.value = (int)converter.ConvertFromString(null, culture, numericPart);
                    }
                    else
                    {
                        TypeConverter converter = new SingleConverter();
                        this.value = (Single)converter.ConvertFromString(null, culture, numericPart);
                    }
                }
                catch {
                    throw new FormatException(SR.GetString(SR.UnitParseNumericPart, value, numericPart, type.ToString("G")));
                }
                if ((this.value < MinValue) || (this.value > MaxValue))
                {
                    throw new ArgumentOutOfRangeException("value");
                }
            }
        }
Пример #30
0
        private static TypeConverter GetCoreConverterFromCoreType(Type type)
        {
            TypeConverter result = null;

            if (type == typeof(int))
            {
                result = new Int32Converter();
            }
            else if (type == typeof(short))
            {
                result = new Int16Converter();
            }
            else if (type == typeof(long))
            {
                result = new Int64Converter();
            }
            else if (type == typeof(uint))
            {
                result = new UInt32Converter();
            }
            else if (type == typeof(ushort))
            {
                result = new UInt16Converter();
            }
            else if (type == typeof(ulong))
            {
                result = new UInt64Converter();
            }
            else if (type == typeof(bool))
            {
                result = new BooleanConverter();
            }
            else if (type == typeof(double))
            {
                result = new DoubleConverter();
            }
            else if (type == typeof(float))
            {
                result = new SingleConverter();
            }
            else if (type == typeof(byte))
            {
                result = new ByteConverter();
            }
            else if (type == typeof(sbyte))
            {
                result = new SByteConverter();
            }
            else if (type == typeof(char))
            {
                result = new CharConverter();
            }
            else if (type == typeof(decimal))
            {
                result = new DecimalConverter();
            }
            else if (type == typeof(TimeSpan))
            {
                result = new TimeSpanConverter();
            }
            else if (type == typeof(Guid))
            {
                result = new GuidConverter();
            }
            else if (type == typeof(string))
            {
                result = new StringConverter();
            }
            else if (type == typeof(CultureInfo))
            {
                result = new CultureInfoConverter();
            }
            else if (type == typeof(Type))
            {
                result = new TypeTypeConverter();
            }
            else if (type == typeof(DateTime))
            {
                result = new DateTimeConverter2();
            }
            else if (ReflectionHelper.IsNullableType(type))
            {
                result = new NullableConverter(type);
            }
            return(result);
        }