Example #1
0
    public bool PosTest4()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest4:UInt32 MaxValue to Type of Int64,double and decimal");

        try
        {
            UInt32       uintA    = UInt32.MaxValue;
            IConvertible iConvert = (IConvertible)(uintA);
            Int64        int64A   = (Int64)iConvert.ToType(typeof(Int64), null);
            Double       doubleA  = (Double)iConvert.ToType(typeof(Double), null);
            Decimal      decimalA = (Decimal)iConvert.ToType(typeof(Decimal), null);
            Single       singleA  = (Single)iConvert.ToType(typeof(Single), null);
            if (int64A != uintA || doubleA != uintA || decimalA != uintA || singleA != uintA)
            {
                TestLibrary.TestFramework.LogError("007", "the ActualResult is not the ExpectResult");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e);
            retVal = false;
        }
        return(retVal);
    }
    public bool PosTest4()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest4:Convert a random UInt64 to Type of double,decimal and single");

        try
        {
            UInt64       uintA    = this.GetInt64(0, UInt64.MaxValue);;
            IConvertible iConvert = (IConvertible)(uintA);
            Double       doubleA  = (Double)iConvert.ToType(typeof(Double), null);
            Decimal      decimalA = (Decimal)iConvert.ToType(typeof(Decimal), null);
            Single       singleA  = (Single)iConvert.ToType(typeof(Single), null);
            if (doubleA != uintA || decimalA != uintA || singleA != uintA)
            {
                TestLibrary.TestFramework.LogError("007", "the ActualResult is not the ExpectResult");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e);
            retVal = false;
        }
        return(retVal);
    }
Example #3
0
        public void TestConvertToType()
        {
            JulianDate         date        = new JulianDate(2451545.0);
            IConvertible       convertible = date as IConvertible;
            DateTimeFormatInfo info        = new DateTimeFormatInfo();

            Assert.AreEqual(date.ToString(), convertible.ToType(typeof(string), info));
            Assert.AreEqual(date.ToDateTime(), convertible.ToType(typeof(DateTime), info));
            Assert.AreEqual(date.TotalDays, convertible.ToType(typeof(double), info));
        }
Example #4
0
    public static TResult CastNew <TResult>(this object _obj)
        where TResult : new()
    {
        if (_obj == null)
        {
            return(new TResult());
        }
        if (_obj is TResult)
        {
            return((TResult)_obj);
        }

        IConvertible res = _obj as IConvertible;

        if (res != null)
        {
            try
            {
                return((TResult)res.ToType(typeof(TResult), Format));
            }
            catch (Exception _ex)
            {
#if UNITY_EDITOR || DEBUG
                Debug.LogWarning("Unable to convert from " + _obj.GetType().Name + " to " + typeof(TResult).Name + ": " + _ex);
#endif
                return(new TResult());
            }
        }

        Debug.LogWarning("Unable to convert from" + _obj.GetType().Name + " to " + typeof(TResult).Name);
        return(new TResult());
    }
Example #5
0
    private bool DoOverflowTest(string testId,
                                string testDesc,
                                string errorNum,
                                Type destType,
                                int destTypeMaxValue)
    {
        bool   retVal = true;
        string errorDesc;

        int    i;
        UInt16 uintA;

        i = Int16.MaxValue + 1 +
            TestLibrary.Generator.GetInt32(-55) % (UInt16.MaxValue - destTypeMaxValue);
        uintA = (UInt16)i;

        TestLibrary.TestFramework.BeginScenario(testDesc);
        try
        {
            IConvertible converter = uintA;
            converter.ToType(destType, null);
        }
        catch (OverflowException)
        { }
        catch (Exception e)
        {
            errorDesc  = "Unexpected exception: " + e;
            errorDesc += string.Format("\nThe UInt16 value is {0}", uintA);
            TestLibrary.TestFramework.LogError(errorNum + " TestId-" + testId, errorDesc);
            retVal = false;
        }

        return(retVal);
    }
 public override bool TryValueOf <T>(BoxedExpression exp, ExpressionType aiType, out T value)
 {
     if (exp.IsConstant)
     {
         object tmpValue = exp.Constant;
         if (tmpValue != null)
         {
             if (tmpValue is T)
             {
                 value = (T)tmpValue;
                 return(true);
             }
             if (tmpValue is String)
             {
                 // early out to avoid format exceptions
                 value = default(T);
                 return(false);
             }
             IConvertible ic = tmpValue as IConvertible;
             if (ic != null)
             {
                 try
                 {
                     value = (T)ic.ToType(typeof(T), null);
                     return(true);
                 }
                 catch
                 {
                 }
             }
         }
     }
     value = default(T);
     return(false);
 }
Example #7
0
 internal static bool TryParse <T>(object input, out T result)
 {
     try {
         result = (T)input;
         return(true);
     }
     catch (InvalidCastException) {
         IConvertible convertible = input as IConvertible;
         if (convertible == null)
         {
             result = default(T);
             return(false);
         }
         else
         {
             try {
                 result = (T)convertible.ToType(typeof(T), CultureInfo.CurrentCulture);
                 return(true);
             }
             catch {
                 result = default(T);
                 return(false);
             }
         }
     }
 }
Example #8
0
        public void DateConvert()
        {
            DateTime     now   = DateTime.Now;
            int          days  = (int)(now.Date - new DateTime(0L, DateTimeKind.Utc).Date).TotalDays;
            Date         today = now.GetDate();
            IConvertible dateTimeConvertible = days;
            IConvertible dateConvertible     = today;

            Assert.AreEqual(dateTimeConvertible.GetTypeCode(), dateConvertible.GetTypeCode());
            TestConversion(dateTimeConvertible.ToBoolean, dateConvertible.ToBoolean);
            TestConversion(dateTimeConvertible.ToByte, dateConvertible.ToByte);
            TestConversion(dateTimeConvertible.ToChar, dateConvertible.ToChar);
            TestConversion(dateTimeConvertible.ToDateTime, dateConvertible.ToDateTime);
            TestConversion(dateTimeConvertible.ToDecimal, dateConvertible.ToDecimal);
            TestConversion(dateTimeConvertible.ToDouble, dateConvertible.ToDouble);
            TestConversion(dateTimeConvertible.ToInt16, dateConvertible.ToInt16);
            TestConversion(dateTimeConvertible.ToInt32, dateConvertible.ToInt32);
            TestConversion(dateTimeConvertible.ToInt64, dateConvertible.ToInt64);
            TestConversion(dateTimeConvertible.ToSByte, dateConvertible.ToSByte);
            TestConversion(dateTimeConvertible.ToSingle, dateConvertible.ToSingle);
            TestConversion(dateTimeConvertible.ToString, dateConvertible.ToString);
            TestConversion(dateTimeConvertible.ToUInt16, dateConvertible.ToUInt16);
            TestConversion(dateTimeConvertible.ToUInt32, dateConvertible.ToUInt32);
            TestConversion(dateTimeConvertible.ToUInt64, dateConvertible.ToUInt64);
            TestConversion(p => dateTimeConvertible.ToType(typeof(double), p), p => dateConvertible.ToType(typeof(double), p));
        }
Example #9
0
    public bool PosTest2()
    {
        bool retVal = true;

        // Add your scenario description here
        TestLibrary.TestFramework.BeginScenario("PosTest2: Convert a random Int32 to Boolean ");

        try
        {
            Int32 i1 = 0;
            while (i1 == 0)
            {
                i1 = TestLibrary.Generator.GetInt32(-55);
            }
            IConvertible Icon1 = (IConvertible)i1;
            bool         s1    = (bool)Icon1.ToType(typeof(System.Boolean), null);
            if (s1 != true)
            {
                TestLibrary.TestFramework.LogError("003", "The result is not the value as expected.The random number is :" + i1.ToString());
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e);
            retVal = false;
        }

        return(retVal);
    }
        public static bool TryParseStruct <T>(this string value, out Nullable <T> result)
            where T : struct
        {
            if (string.IsNullOrEmpty(value))
            {
                result = new Nullable <T>();

                return(true);
            }

            result = default(T);
            try
            {
                IConvertible convertibleString = (IConvertible)value;
                result = new Nullable <T>((T)convertibleString.ToType(typeof(T), System.Globalization.CultureInfo.CurrentCulture));
            }
            catch (InvalidCastException)
            {
                return(false);
            }
            catch (FormatException)
            {
                return(false);
            }

            return(true);
        }
Example #11
0
        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            object type = null;

            try
            {
                IConvertible convertible = (IConvertible)value;
                if (convertible != null)
                {
                    type = convertible.ToType(typeof(T), culture);
                    return(type);
                }
            }
            catch (FormatException formatException)
            {
                if ((value == null || !(value.ToString().Equals("AUTO", StringComparison.CurrentCultureIgnoreCase))) ? true : false)
                {
                    throw;
                }
                else
                {
                    type = double.NaN;

                    return(type);
                }
            }
            type = null;
            return(type);
        }
Example #12
0
        public T GetValue <T>(T defaultValue)
        {
            if (typeof(Wz_Image) == typeof(T) && this is Wz_Image.Wz_ImageNode)
            {
                return((T)(object)(((Wz_Image.Wz_ImageNode) this).Image));
            }
            if (this.value == null)
            {
                return(defaultValue);
            }
            if (this.value.GetType() == typeof(T))
            {
                return((T)this.value);
            }

            IConvertible iconvertible = this.value as IConvertible;

            if (iconvertible != null)
            {
                try
                {
                    T result = (T)iconvertible.ToType(typeof(T), null);
                    return(result);
                }
                catch
                {
                }
            }
            return(defaultValue);
        }
        public static bool TryParse(string s, out T result, T defaultValue)
        {
            bool success = false;

            result = default;
            if (String.IsNullOrEmpty(s))
            {
                result  = defaultValue;
                success = true;
            }
            else
            {
#pragma warning disable IDE0019 // Use pattern matching
                IConvertible convertableString = s as IConvertible;
#pragma warning restore IDE0019 // Use pattern matching
                if (convertableString != null)
                {
                    try
                    {
                        result  = (T)convertableString.ToType(typeof(T), CultureInfo.CurrentCulture);
                        success = true;
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.Write(ex);
                    }
                }
            }
            return(success);
        }
Example #14
0
    public bool PosTest1()
    {
        bool retVal = true;

        // Add your scenario description here
        TestLibrary.TestFramework.BeginScenario("PosTest1: Convert a random Int32 to String ");

        try
        {
            Int32        i1    = TestLibrary.Generator.GetInt32(-55);
            IConvertible Icon1 = (IConvertible)i1;
            string       s1    = Icon1.ToType(typeof(System.String), null) as string;
            if (s1 != i1.ToString())
            {
                TestLibrary.TestFramework.LogError("001", "The result is not the value as expected.The random number is :" + i1.ToString());
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
            retVal = false;
        }

        return(retVal);
    }
Example #15
0
    public bool NegTest1()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("NegTest1: Test the overflowException ");

        try
        {
            Int32 i1 = 0;
            while (i1 <= 255)
            {
                i1 = TestLibrary.Generator.GetInt32(-55);
            }
            IConvertible Icon1 = (IConvertible)i1;
            byte         s1    = (byte)Icon1.ToType(typeof(System.Byte), null);
            TestLibrary.TestFramework.LogError("101", "The overflow exception was not thrown as expected: ");
            retVal = false;
        }
        catch (OverflowException)
        {
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("102", "Unexpected exception: " + e);
            retVal = false;
        }

        return(retVal);
    }
Example #16
0
    public bool PosTest4()
    {
        bool retVal = true;

        // Add your scenario description here
        TestLibrary.TestFramework.BeginScenario("PosTest4: Convert \'-0\' to char ");

        try
        {
            Int32        i1    = -0;
            IConvertible Icon1 = (IConvertible)i1;
            char         s1    = (char)Icon1.ToType(typeof(System.Char), null);
            if (s1 != '\0')
            {
                TestLibrary.TestFramework.LogError("007", "The result is not the value as expected.");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e);
            retVal = false;
        }

        return(retVal);
    }
Example #17
0
    public bool PosTest3()
    {
        bool retVal = true;

        // Add your scenario description here
        TestLibrary.TestFramework.BeginScenario("PosTest3: Check the boundary value ");

        try
        {
            Int32        i1    = Int32.MaxValue;
            IConvertible Icon1 = (IConvertible)i1;
            long         s1    = (long)Icon1.ToType(typeof(System.Int64), null);
            if (s1 != i1)
            {
                TestLibrary.TestFramework.LogError("005", "The result is not the value as expected.");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e);
            retVal = false;
        }

        return(retVal);
    }
Example #18
0
    //ArgumentNullException
    public bool NegTest1()
    {
        bool retVal = true;

        const string c_TEST_ID   = "N001";
        const string c_TEST_DESC = "NegTest1: type is a null reference (Nothing in Visual Basic).";
        string       errorDesc;

        char ch = TestLibrary.Generator.GetChar(-55);

        TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
        try
        {
            IConvertible converter = ch;
            converter.ToType(null, null);

            errorDesc  = "ArgumentNullException is not thrown as expected.";
            errorDesc += string.Format("\nThe character is \\u{0:x}", (int)ch);
            TestLibrary.TestFramework.LogError("021" + " TestId-" + c_TEST_ID, errorDesc);
            retVal = false;
        }
        catch (ArgumentNullException)
        { }
        catch (Exception e)
        {
            errorDesc  = "Unexpected exception: " + e;
            errorDesc += string.Format("\nThe character is \\u{0:x}", (int)ch);
            TestLibrary.TestFramework.LogError("022" + " TestId-" + c_TEST_ID, errorDesc);
            retVal = false;
        }

        return(retVal);
    }
Example #19
0
        public static T GetValue <T>(string name, T defaultvalue = null, string strConfigPath = "") where T : class
        {
            T t = default(T);
            T result;

            if (ConfigurationManager.AppSettings.AllKeys.Contains(name))
            {
                IConvertible convertible = ConfigurationManager.AppSettings[name];
                t      = (T)((object)convertible.ToType(typeof(T), null));
                result = t;
            }
            else
            {
                if (!string.IsNullOrEmpty(strConfigPath))
                {
                    Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(new ExeConfigurationFileMap
                    {
                        ExeConfigFilename = strConfigPath
                    }, ConfigurationUserLevel.None);
                    if (configuration.AppSettings.Settings.AllKeys.Contains(name))
                    {
                        result = (T)((object)Convert.ChangeType(configuration.AppSettings.Settings[name].Value, typeof(T)));
                        return(result);
                    }
                }
                result = defaultvalue;
            }
            return(result);
        }
Example #20
0
    public bool PosTest3()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest3: Convert an enum of negative value to single");

        try
        {
            e_test       e1 = e_test.itemA;
            IConvertible i1 = e1 as IConvertible;
            float        s1 = (float)i1.ToType(typeof(float), null);
            if (s1 != -123456789.0f)
            {
                TestLibrary.TestFramework.LogError("005", "The result is not the value as expected");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e);
            retVal = false;
        }

        return(retVal);
    }
Example #21
0
    public bool PosTest1()
    {
        bool retVal = true;


        TestLibrary.TestFramework.BeginScenario("PosTest1: Convert an enum to string ");

        try
        {
            color        c1 = color.blue;
            IConvertible i1 = c1 as IConvertible;
            string       s1 = i1.ToType(typeof(string), null) as string;
            if (s1 != "blue")
            {
                TestLibrary.TestFramework.LogError("001", "The result is not the value as expected");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
            retVal = false;
        }

        return(retVal);
    }
Example #22
0
    public bool PosTest2()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest2:  Convert an enum to byte");

        try
        {
            color        c1 = color.white;
            IConvertible i1 = c1 as IConvertible;
            byte         s1 = (byte)i1.ToType(typeof(byte), null);
            if (s1 != 101)
            {
                TestLibrary.TestFramework.LogError("003", "The result is not the value as expected");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e);
            retVal = false;
        }

        return(retVal);
    }
Example #23
0
    public bool PosTest6()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest6:Set the first argument as type of double");

        try
        {
            e_test       e1 = e_test.itemC;
            IConvertible i1 = e1 as IConvertible;
            double       s1 = (double)i1.ToType(typeof(double), null);
            if (s1 != (double)Int64.MaxValue)
            {
                TestLibrary.TestFramework.LogError("011", "The result is not the value as expected");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("012", "Unexpected exception: " + e);
            retVal = false;
        }

        return(retVal);
    }
Example #24
0
    public bool NegTest1()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("NegTest1: Convert an enum of int32 to int16");

        try
        {
            e_test       e1 = e_test.itemB;
            IConvertible i1 = e1 as IConvertible;
            Int16        s1 = (Int16)i1.ToType(typeof(Int16), null);
            TestLibrary.TestFramework.LogError("101", "The OverflowException was not thrown as expected");
            retVal = false;
        }
        catch (OverflowException)
        {
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("102", "Unexpected exception: " + e);
            retVal = false;
        }

        return(retVal);
    }
Example #25
0
    public bool PosTest4()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest4: Convert an enum of int64.MaxValue to Int64 ");

        try
        {
            e_test       e1 = e_test.itemC;
            IConvertible i1 = e1 as IConvertible;
            long         s1 = (long)i1.ToType(typeof(long), null);
            if (s1 != Int64.MaxValue)
            {
                TestLibrary.TestFramework.LogError("007", "The result is not the value as expected");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e);
            retVal = false;
        }

        return(retVal);
    }
Example #26
0
    public bool PosTest5()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest5: Convert an enum of int32.MinValue to Int32");

        try
        {
            e_test       e1 = e_test.itemB;
            IConvertible i1 = e1 as IConvertible;
            int          s1 = (int)i1.ToType(typeof(int), null);
            if (s1 != Int32.MinValue)
            {
                TestLibrary.TestFramework.LogError("009", "The result is not the value as expected");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("010", "Unexpected exception: " + e);
            retVal = false;
        }

        return(retVal);
    }
Example #27
0
    private bool DoInvalidCastTest(string testId,
                                   string testDesc,
                                   string errorNum1,
                                   string errorNum2,
                                   Type destType)
    {
        bool   retVal = true;
        string errorDesc;

        char ch = TestLibrary.Generator.GetChar(-55);

        TestLibrary.TestFramework.BeginScenario(testDesc);
        try
        {
            IConvertible converter = ch;
            converter.ToType(destType, null);

            errorDesc  = "InvalidCastException is not thrown as expected.";
            errorDesc += string.Format("\nThe character is \\u{0:x}", (int)ch);
            TestLibrary.TestFramework.LogError(errorNum1 + " TestId-" + testId, errorDesc);
            retVal = false;
        }
        catch (InvalidCastException)
        { }
        catch (Exception e)
        {
            errorDesc  = "Unexpected exception: " + e;
            errorDesc += string.Format("\nThe character is \\u{0:x}", (int)ch);
            TestLibrary.TestFramework.LogError(errorNum2 + " TestId-" + testId, errorDesc);
            retVal = false;
        }

        return(retVal);
    }
    public bool PosTest1()
    {
        bool            retVal    = true;
        CultureInfo     myculture = new CultureInfo("en-us");
        IFormatProvider provider  = myculture.NumberFormat;

        TestLibrary.TestFramework.BeginScenario("PosTest1:The Int64 MinValue IConvertible to Type 1");
        try
        {
            long         int64A   = Int64.MinValue;
            IConvertible iConvert = (IConvertible)(int64A);
            object       objA     = iConvert.ToType(typeof(Int64), provider);
            if ((long)objA != c_INT64_MinValue)
            {
                TestLibrary.TestFramework.LogError("001", "the ActualResult is not the ExpectResult");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
            retVal = false;
        }
        return(retVal);
    }
Example #29
0
    public bool NegTest2()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("NegTest2: Convert an int16 to a custom class type ");

        try
        {
            Int16        i1          = TestLibrary.Generator.GetInt16(-55);
            IConvertible Icon1       = (IConvertible)i1;
            CultureInfo  cultureinfo = new CultureInfo("en-US");
            TestClass    testclass   = Icon1.ToType(typeof(TestClass), cultureinfo) as TestClass;
            TestLibrary.TestFramework.LogError("103", "The InvalidCastException was not thrown as expected: " + i1);
            retVal = false;
        }
        catch (InvalidCastException)
        {
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("104", "Unexpected exception: " + e);
            retVal = false;
        }

        return(retVal);
    }
Example #30
0
        public void ValuesAreConvertible()
        {
            RedisValue val = 123;
            object     o   = val;

            byte[] blob = (byte[])Convert.ChangeType(o, typeof(byte[]));

            Assert.AreEqual(3, blob.Length);
            Assert.AreEqual((byte)'1', blob[0]);
            Assert.AreEqual((byte)'2', blob[1]);
            Assert.AreEqual((byte)'3', blob[2]);

            Assert.AreEqual((double)123, Convert.ToDouble(o));

            IConvertible c = (IConvertible)o;

            Assert.AreEqual((short)123, c.ToInt16(CultureInfo.InvariantCulture));
            Assert.AreEqual((int)123, c.ToInt32(CultureInfo.InvariantCulture));
            Assert.AreEqual((long)123, c.ToInt64(CultureInfo.InvariantCulture));
            Assert.AreEqual((float)123, c.ToSingle(CultureInfo.InvariantCulture));
            Assert.AreEqual("123", c.ToString(CultureInfo.InvariantCulture));
            Assert.AreEqual((double)123, c.ToDouble(CultureInfo.InvariantCulture));
            Assert.AreEqual((decimal)123, c.ToDecimal(CultureInfo.InvariantCulture));
            Assert.AreEqual((ushort)123, c.ToUInt16(CultureInfo.InvariantCulture));
            Assert.AreEqual((uint)123, c.ToUInt32(CultureInfo.InvariantCulture));
            Assert.AreEqual((ulong)123, c.ToUInt64(CultureInfo.InvariantCulture));

            blob = (byte[])c.ToType(typeof(byte[]), CultureInfo.InvariantCulture);
            Assert.AreEqual(3, blob.Length);
            Assert.AreEqual((byte)'1', blob[0]);
            Assert.AreEqual((byte)'2', blob[1]);
            Assert.AreEqual((byte)'3', blob[2]);
        }
Example #31
0
        public void SetProperty(string property, IConvertible prop_val)
        {
            PropertyInfo prop_info = item.GetType ().GetProperty (property);

            if (prop_info == null)
                throw new ApplicationException (String.Format (
                    "Unable to set property {0}.{1} to \"{2}\"",
                    item.GetType (), property, prop_val));

            Type prop_type = prop_info.PropertyType;
            object param;

            try {
                param = prop_val.ToType (prop_type, NumberFormatInfo.InvariantInfo);
            } catch (FormatException e) {
                throw new ApplicationException (String.Format (
                    "prop_val cannot be converted to a {0}", prop_type), e);
            }

            prop_info.SetValue (item, param, null);
        }
			public void Case(IConvertible value)
			{
				bool duplicate;

				// make sure the value is of the governing type
				IComparable val = value == null ? null : (IComparable)value.ToType(govType, System.Globalization.CultureInfo.InvariantCulture);

				if (value == null)
					duplicate = defaultExists;
				else
					duplicate = cases.ContainsKey(val);

				if (duplicate)
					throw new InvalidOperationException(Properties.Messages.ErrDuplicateCase);

				if (g.reachable)
					g.il.Emit(OpCodes.Br, lbEnd);

				EndScope();
				Label lb = g.il.DefineLabel();
				g.il.MarkLabel(lb);
				if (value == null)
				{
					defaultExists = true;
					lbDefault = lb;
				}
				else
				{
					cases[val] = lb;
				}
				g.reachable = true;
			}
 protected virtual bool SetValue(object instance, PropertyInfo property, IConvertible oValue)
 {
     try {
         object convertedValue = oValue.ToType(property.PropertyType, CultureInfo.CurrentCulture);
         return SetValue(instance, property, convertedValue);
     }
     catch {
         return false;
     }
 }
Example #34
0
	// Default implementation of the "ToType" methods in
	// the primitive classes like Byte, Int32, Boolean, etc.
	internal static Object DefaultToType(IConvertible obj, Type targetType,
										 IFormatProvider provider,
										 bool recursive)
			{
				if(targetType != null)
				{
					if(obj.GetType() == targetType)
					{
						return obj;
					}
					else if(targetType == ConvertTypes[(int)TypeCode.Boolean])
					{
						return (Object)(obj.ToBoolean(provider));
					}
					else if(targetType == ConvertTypes[(int)TypeCode.Char])
					{
						return (Object)(obj.ToChar(provider));
					}
					else if(targetType == ConvertTypes[(int)TypeCode.SByte])
					{
						return (Object)(obj.ToSByte(provider));
					}
					else if(targetType == ConvertTypes[(int)TypeCode.Byte])
					{
						return (Object)(obj.ToByte(provider));
					}
					else if(targetType == ConvertTypes[(int)TypeCode.Int16])
					{
						return (Object)(obj.ToInt16(provider));
					}
					else if(targetType == ConvertTypes[(int)TypeCode.UInt16])
					{
						return (Object)(obj.ToUInt16(provider));
					}
					else if(targetType == ConvertTypes[(int)TypeCode.Int32])
					{
						return (Object)(obj.ToInt32(provider));
					}
					else if(targetType == ConvertTypes[(int)TypeCode.UInt32])
					{
						return (Object)(obj.ToUInt32(provider));
					}
					else if(targetType == ConvertTypes[(int)TypeCode.Int64])
					{
						return (Object)(obj.ToInt64(provider));
					}
					else if(targetType == ConvertTypes[(int)TypeCode.UInt64])
					{
						return (Object)(obj.ToUInt64(provider));
					}
					else if(targetType == ConvertTypes[(int)TypeCode.Single])
					{
						return (Object)(obj.ToSingle(provider));
					}
					else if(targetType == ConvertTypes[(int)TypeCode.Double])
					{
						return (Object)(obj.ToDouble(provider));
					}
					else if(targetType == ConvertTypes[(int)TypeCode.Decimal])
					{
						return (Object)(obj.ToDecimal(provider));
					}
					else if(targetType == ConvertTypes[(int)TypeCode.DateTime])
					{
						return (Object)(obj.ToDateTime(provider));
					}
					else if(targetType == ConvertTypes[(int)TypeCode.String])
					{
						return (Object)(obj.ToString(provider));
					}
					else if(targetType == ConvertTypes[(int)TypeCode.Object])
					{
						return obj;
					}
					else if(targetType == ConvertTypes[(int)TypeCode.Empty])
					{
						throw new InvalidCastException
							(_("InvalidCast_Empty"));
					}
					else if(targetType == ConvertTypes[(int)TypeCode.DBNull])
					{
						throw new InvalidCastException
							(_("InvalidCast_DBNull"));
					}
					else if(recursive)
					{
						throw new InvalidCastException
							(String.Format
								(_("InvalidCast_FromTo"),
		 					     obj.GetType().FullName, targetType.FullName));
					}
					else
					{
						// We weren't called from a "ToType" method,
						// so we can use it to handle the default case.
						return obj.ToType(targetType, provider);
					}
				}
				else
				{
					throw new ArgumentNullException("targetType");
				}
			}