ConvertFrom() public method

public ConvertFrom ( ITypeDescriptorContext context, CultureInfo culture, object value ) : object
context ITypeDescriptorContext
culture System.Globalization.CultureInfo
value object
return object
        /// <inheritdoc />
        public override bool TryConvert(object value, Type destinationType, out object result, ConversionArgs args)
        {
            System.ComponentModel.TypeConverter converter = TypeDescriptor.GetConverter(destinationType);
            if (converter.GetType() != typeof(System.ComponentModel.TypeConverter) && converter.CanConvertFrom(value.GetType()))
            {
                try {
                    result = converter.ConvertFrom(null, args.Culture, value);
                    return(true);
                }
                catch {
                }
            }

            converter = TypeDescriptor.GetConverter(value.GetType());
            if (converter.GetType() != typeof(System.ComponentModel.TypeConverter) && converter.CanConvertTo(destinationType))
            {
                try {
                    result = converter.ConvertTo(null, args.Culture, value, destinationType);
                    return(true);
                }
                catch {
                }
            }

            result = null;
            return(false);
        }
        private static bool InnerConvertObjectToType(object obj, Type type, bool throwOnError,
                                                     out object convertedObject)
        {
            Type originalType = obj.GetType();
            OriginalTypeConverter converter = TypeDescriptor.GetConverter(type);

            if (converter.CanConvertFrom(originalType))
            {
                try
                {
                    convertedObject = converter.ConvertFrom(null, CultureInfo.InvariantCulture, obj);
                    return(true);
                }
                catch
                {
                    if (throwOnError)
                    {
                        throw;
                    }

                    convertedObject = null;
                    return(false);
                }
            }

            if (converter.CanConvertFrom(typeof(string)) && !(obj is DateTime))
            {
                try
                {
                    string text = TypeDescriptor.GetConverter(originalType).ConvertToInvariantString(obj);

                    convertedObject = converter.ConvertFromInvariantString(text);
                    return(true);
                }
                catch
                {
                    if (throwOnError)
                    {
                        throw;
                    }

                    convertedObject = null;
                    return(false);
                }
            }

            if (type.IsInstanceOfType(obj))
            {
                convertedObject = obj;
                return(true);
            }

            if (throwOnError)
            {
                throw new InvalidOperationException();
            }

            convertedObject = null;
            return(false);
        }
Exemplo n.º 3
0
        /// <summary>
        /// 转换简单类型
        /// </summary>
        /// <param name="value"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        private static object ConvertObj(object value, Type type)
        {
            object returnValue;

            if ((value == null) || type.IsInstanceOfType(value))
            {
                return(value);
            }
            string str = value as string;

            if ((str != null) && (str.Length == 0))
            {
                return(null);
            }
            System.ComponentModel.TypeConverter converter = TypeDescriptor.GetConverter(type);
            bool flag = converter.CanConvertFrom(value.GetType());

            if (!flag)
            {
                converter = TypeDescriptor.GetConverter(value.GetType());
            }
            if (!flag && !converter.CanConvertTo(type))
            {
                throw new InvalidOperationException("无法转换成类型:" + value.ToString() + "==>" + type);
            }
            try
            {
                returnValue = flag ? converter.ConvertFrom(null, null, value) : converter.ConvertTo(null, null, value, type);
            }
            catch (Exception e)
            {
                throw new InvalidOperationException("类型转换出错:" + value.ToString() + "==>" + type, e);
            }
            return(returnValue);
        }
Exemplo n.º 4
0
 private object GetValue(DateTime dateTime, Type type, TypeConverter converter)
 {
     if (type.IsAssignableFrom(typeof(DateTime)))
         return dateTime;
     else
         return converter.ConvertFrom(dateTime);
 }
Exemplo n.º 5
0
    void TypeConverters()
    {
        System.ComponentModel.TypeConverter testConverter
            = System.ComponentModel.TypeDescriptor.GetConverter(typeof(System.Drawing.Color));

        System.Drawing.Color result = (System.Drawing.Color)testConverter.ConvertFrom("cyan");
        var alt = System.Drawing.Color.FromName("cyan");

        Console.WriteLine(result);
        Console.WriteLine(alt == result);
    }
Exemplo n.º 6
0
        private static SqlDbType GetDBType(Type theType)
        {
            SqlParameter p1 = new SqlParameter();

            System.ComponentModel.TypeConverter tc = System.ComponentModel.TypeDescriptor.GetConverter(p1.DbType);
            if (tc.CanConvertFrom(theType))
            {
                p1.DbType = (DbType)tc.ConvertFrom(theType.Name);
            }
            else
            {
                //Try brute force
                try
                {
                    p1.DbType = (DbType)tc.ConvertFrom(theType.Name);
                }
                catch { } //Do Nothing
            }
            return(p1.SqlDbType);
        }
Exemplo n.º 7
0
		private void SetValueFromConverter(string newValue, Type targetType, TypeConverter converter)
		{
			if (!converter.CanConvertFrom(targetType) && string.IsNullOrEmpty(newValue))
			{
				this.Value = null;
			}
			else
			{
				this.Value = converter.ConvertFrom(newValue);
			}
		}
Exemplo n.º 8
0
        public static T ConvertType <T>(string value)
        {
            if (typeof(T).IsEnum)
            {
                return((T)Enum.Parse(typeof(T), value));
            }

            System.ComponentModel.TypeConverter converter = TypeDescriptor.GetConverter(typeof(T));
            if (converter != null && converter.CanConvertFrom(value.GetType()))
            {
                return((T)converter.ConvertFrom(value));
            }
            else
            {
                return((T)Convert.ChangeType(value, typeof(T)));
            }
        }
Exemplo n.º 9
0
        //-------------------------------------------------------------------------------------------------
        public static object ConvertType(string value, Type type)
        {
            if (type.IsEnum)
            {
                return(Enum.Parse(type, value));
            }

            System.ComponentModel.TypeConverter converter = TypeDescriptor.GetConverter(type);
            if (converter != null && converter.CanConvertFrom(value.GetType()))
            {
                return(converter.ConvertFrom(value));
            }
            else
            {
                return(Convert.ChangeType(value, type));
            }
        }
Exemplo n.º 10
0
        private static object ConvertSimpleType(CultureInfo culture, object value, Type destinationType)
        {
            if (value == null || destinationType.IsInstanceOfType(value))
            {
                return(value);
            }

            // if this is a user-input value but the user didn't type anything, return no value
            string valueAsString = value as string;

            if (valueAsString != null && valueAsString.Trim().Length == 0)
            {
                return(null);
            }

            //modified by Yang Li
            //TypeConverter converter = TypeDescriptor.GetConverter(destinationType);
            System.ComponentModel.TypeConverter converter = TypeDescriptor.GetConverter(destinationType);
            bool canConvertFrom = converter.CanConvertFrom(value.GetType());

            if (!canConvertFrom)
            {
                converter = TypeDescriptor.GetConverter(value.GetType());
            }
            if (!(canConvertFrom || converter.CanConvertTo(destinationType)))
            {
                string message = String.Format(CultureInfo.CurrentCulture, MvcResources.ValueProviderResult_NoConverterExists,
                                               value.GetType().FullName, destinationType.FullName);
                throw new InvalidOperationException(message);
            }

            try
            {
                object convertedValue = (canConvertFrom) ?
                                        converter.ConvertFrom(null /* context */, culture, value) :
                                        converter.ConvertTo(null /* context */, culture, value, destinationType);
                return(convertedValue);
            }
            catch (Exception ex)
            {
                string message = String.Format(CultureInfo.CurrentCulture, MvcResources.ValueProviderResult_ConversionThrew,
                                               value.GetType().FullName, destinationType.FullName);
                throw new InvalidOperationException(message, ex);
            }
        }
 /// <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"></see> that provides a format context.</param>
 /// <param name="culture">The <see cref="T:System.Globalization.CultureInfo"></see> to use as the current culture.</param>
 /// <param name="value">The <see cref="T:System.Object"></see> to convert.</param>
 /// <returns>
 /// An <see cref="T:System.Object"></see> that represents the converted value.
 /// </returns>
 /// <exception cref="T:System.NotSupportedException">The conversion can not be performed. </exception>
 public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, CultureInfo culture, object value)
 {
     if (value != null && value.GetType() == typeof(string))
     {
         if (parseFormats != null)
         {
             return(DateTime.ParseExact((string)value, parseFormats, GetCulture(culture).DateTimeFormat, dateTimeStyles));
         }
         else
         {
             return(DateTime.Parse((string)value, GetCulture(culture).DateTimeFormat, dateTimeStyles));
         }
     }
     else
     {
         return(baseTypeConverter.ConvertFrom(context, culture, value));
     }
 }
Exemplo n.º 12
0
        protected override Resources.PDFImageXObject InitImageXObject(PDFContextBase context, Style style)
        {
            Document doc = this.Document;

            if (null == doc)
            {
                throw new NullReferenceException(Errors.ParentDocumentCannotBeNull);
            }

            if (null != this.Data)
            {
                _xobj = null;
                if (!string.IsNullOrEmpty(this.ImageKey))
                {
                    _xobj = this.Document.GetImageResource(this.ImageKey, this, false);
                }

                if (null == _xobj)
                {
                    string name;
                    if (string.IsNullOrEmpty(this.ImageKey))
                    {
                        name = "DataImage_" + this.Document.GetIncrementID(PDFObjectTypes.ImageXObject);
                    }
                    else
                    {
                        name = this.ImageKey;
                    }

                    System.ComponentModel.TypeConverter BitmapConverter = TypeDescriptor.GetConverter(typeof(Bitmap));
                    Bitmap img = (Bitmap)BitmapConverter.ConvertFrom(this.Data.Raw);


                    PDFImageData data = PDFImageData.LoadImageFromBitmap(name, img, this.Compress);

                    _xobj = PDFImageXObject.Load(data, name);
                    this.Document.SharedResources.Add(_xobj);
                }
            }

            return(_xobj);
        }
Exemplo n.º 13
0
 public static object ConvertToType(string value, Type type)
 {
     if (type == null)
     {
         return(null);
     }
     System.ComponentModel.TypeConverter conv = System.ComponentModel.TypeDescriptor.GetConverter(type);
     if (conv.CanConvertFrom(typeof(string)))
     {
         try
         {
             return(conv.ConvertFrom(value));
         }
         catch
         {
             return(null);
         }
     }
     return(null);
 }
Exemplo n.º 14
0
        public bool LoadDir(string DirPath, List <string> crFiles, Color Transparency)
        {
            List <string> filenames = new List <string>();

            foreach (var path in this.EditorData.GraphicsPaths)
            {
                var fullPath = DirPath + Path.DirectorySeparatorChar + path;
                if (Directory.Exists(fullPath))
                {
                    filenames.AddRange(Directory.GetFiles(fullPath));
                }
            }
            foreach (var crFile in crFiles)
            {
                foreach (var filename in filenames)
                {
                    string ext = Path.GetExtension(filename).ToLower();
                    if (!(ext == ".frm" || ext == ".png"))
                    {
                        continue;
                    }
                    byte[] bytes = File.ReadAllBytes(filename);
                    if (ext == ".frm")
                    {
                        var frm = FalloutFRMLoader.LoadFRM(bytes, Transparency);
                        Frms[filename] = frm;
                    }
                    else
                    {
                        System.ComponentModel.TypeConverter tc = System.ComponentModel.TypeDescriptor.GetConverter(typeof(Bitmap));
                        Bitmap bitmap = (Bitmap)tc.ConvertFrom(bytes);
                        Frms[filename]        = new FalloutFRM();
                        Frms[filename].Frames = new List <Bitmap>();
                        Frms[filename].Frames.Add(bitmap);
                        Frms[filename].FileName = filename.Remove(filename.IndexOf(DirPath), DirPath.Length);
                    }
                }
            }
            return(true);
        }
Exemplo n.º 15
0
		object ConvertData (TypeConverter c)
		{
			if (mime_type == ResXResourceWriter.ByteArraySerializedObjectMimeType) {
				if (c.CanConvertFrom (typeof (byte [])))
					return c.ConvertFrom (Convert.FromBase64String (dataString));
			} else if (String.IsNullOrEmpty (mime_type)) {
				if (c.CanConvertFrom (typeof (string)))
					return c.ConvertFromInvariantString (dataString);
			}
			else
				throw new Exception ("shouldnt get here, invalid mime type");

			throw new TypeLoadException ("No converter for this type found");
		}
 private static object FormatObjectInternal(object value, System.Type targetType, TypeConverter sourceConverter, TypeConverter targetConverter, string formatString, IFormatProvider formatInfo, object formattedNullValue)
 {
     if ((value == DBNull.Value) || (value == null))
     {
         if (formattedNullValue != null)
         {
             return formattedNullValue;
         }
         if (targetType == stringType)
         {
             return string.Empty;
         }
         if (targetType == checkStateType)
         {
             return CheckState.Indeterminate;
         }
         return null;
     }
     if (((targetType == stringType) && (value is IFormattable)) && !string.IsNullOrEmpty(formatString))
     {
         return (value as IFormattable).ToString(formatString, formatInfo);
     }
     System.Type type = value.GetType();
     TypeConverter converter = TypeDescriptor.GetConverter(type);
     if (((sourceConverter != null) && (sourceConverter != converter)) && sourceConverter.CanConvertTo(targetType))
     {
         return sourceConverter.ConvertTo(null, GetFormatterCulture(formatInfo), value, targetType);
     }
     TypeConverter converter2 = TypeDescriptor.GetConverter(targetType);
     if (((targetConverter != null) && (targetConverter != converter2)) && targetConverter.CanConvertFrom(type))
     {
         return targetConverter.ConvertFrom(null, GetFormatterCulture(formatInfo), value);
     }
     if (targetType == checkStateType)
     {
         if (type == booleanType)
         {
             return (((bool) value) ? CheckState.Checked : CheckState.Unchecked);
         }
         if (sourceConverter == null)
         {
             sourceConverter = converter;
         }
         if ((sourceConverter != null) && sourceConverter.CanConvertTo(booleanType))
         {
             return (((bool) sourceConverter.ConvertTo(null, GetFormatterCulture(formatInfo), value, booleanType)) ? CheckState.Checked : CheckState.Unchecked);
         }
     }
     if (targetType.IsAssignableFrom(type))
     {
         return value;
     }
     if (sourceConverter == null)
     {
         sourceConverter = converter;
     }
     if (targetConverter == null)
     {
         targetConverter = converter2;
     }
     if ((sourceConverter != null) && sourceConverter.CanConvertTo(targetType))
     {
         return sourceConverter.ConvertTo(null, GetFormatterCulture(formatInfo), value, targetType);
     }
     if ((targetConverter != null) && targetConverter.CanConvertFrom(type))
     {
         return targetConverter.ConvertFrom(null, GetFormatterCulture(formatInfo), value);
     }
     if (!(value is IConvertible))
     {
         throw new FormatException(GetCantConvertMessage(value, targetType));
     }
     return ChangeType(value, targetType, formatInfo);
 }
 private static object ParseObjectInternal(object value, System.Type targetType, System.Type sourceType, TypeConverter targetConverter, TypeConverter sourceConverter, IFormatProvider formatInfo, object formattedNullValue)
 {
     if (EqualsFormattedNullValue(value, formattedNullValue, formatInfo) || (value == DBNull.Value))
     {
         return DBNull.Value;
     }
     TypeConverter converter = TypeDescriptor.GetConverter(targetType);
     if (((targetConverter != null) && (converter != targetConverter)) && targetConverter.CanConvertFrom(sourceType))
     {
         return targetConverter.ConvertFrom(null, GetFormatterCulture(formatInfo), value);
     }
     TypeConverter converter2 = TypeDescriptor.GetConverter(sourceType);
     if (((sourceConverter != null) && (converter2 != sourceConverter)) && sourceConverter.CanConvertTo(targetType))
     {
         return sourceConverter.ConvertTo(null, GetFormatterCulture(formatInfo), value, targetType);
     }
     if (value is string)
     {
         object obj2 = InvokeStringParseMethod(value, targetType, formatInfo);
         if (obj2 != parseMethodNotFound)
         {
             return obj2;
         }
     }
     else if (value is CheckState)
     {
         CheckState state = (CheckState) value;
         if (state == CheckState.Indeterminate)
         {
             return DBNull.Value;
         }
         if (targetType == booleanType)
         {
             return (state == CheckState.Checked);
         }
         if (targetConverter == null)
         {
             targetConverter = converter;
         }
         if ((targetConverter != null) && targetConverter.CanConvertFrom(booleanType))
         {
             return targetConverter.ConvertFrom(null, GetFormatterCulture(formatInfo), state == CheckState.Checked);
         }
     }
     else if ((value != null) && targetType.IsAssignableFrom(value.GetType()))
     {
         return value;
     }
     if (targetConverter == null)
     {
         targetConverter = converter;
     }
     if (sourceConverter == null)
     {
         sourceConverter = converter2;
     }
     if ((targetConverter != null) && targetConverter.CanConvertFrom(sourceType))
     {
         return targetConverter.ConvertFrom(null, GetFormatterCulture(formatInfo), value);
     }
     if ((sourceConverter != null) && sourceConverter.CanConvertTo(targetType))
     {
         return sourceConverter.ConvertTo(null, GetFormatterCulture(formatInfo), value, targetType);
     }
     if (!(value is IConvertible))
     {
         throw new FormatException(GetCantConvertMessage(value, targetType));
     }
     return ChangeType(value, targetType, formatInfo);
 }
        /// <summary>
        /// ��ȡ"Value"�ڵ�
        /// �������ԣ��������ĵ��е�����ֵ�������͵�ת����ת��Ϊ��ǰ���Ե�ֵ����
        /// </summary>
        /// <param name="node">���ڵ�</param>
        /// <param name="converter">���͵�ת����</param>  
        /// <param name="value">����</param>
        /// <returns>��ֵ�Ƿ��ܹ���ת������Ҫ������</returns>
        private bool ReadValue(XmlNode node, TypeConverter converter, ref object value)
        {
            try
            {
                foreach (XmlNode child in node.ChildNodes)
                {
                    //XmlNodeTypeö��ָ���ڵ�����͡�.Text:�ڵ���ı����ݡ�Text �ڵ㲻�ܾ����κ��ӽڵ㡣
                    if (child.NodeType == XmlNodeType.Text)
                    {
                        value = converter.ConvertFromInvariantString(node.InnerText);
                        return true;
                    }
                    else if (child.NodeType == XmlNodeType.Element)
                    {//������Ϣ�ڵ����ô˲��ֶ�ȡ����ӿ���Ϣ20090616
                        List<string> tempIO = new List<string>();
                        for (int i = 0; i < node.ChildNodes.Count; i++)
                        {
                            tempIO.Add(node.ChildNodes[i].Attributes["name"].Value);
                        }
                        value = String.Join(",", tempIO.ToArray());
                        return true;
                    }
                    else if (child.Name.Equals("Binary"))
                    {
                        byte[] data = Convert.FromBase64String(child.InnerText);

                        if (GetConversionSupported(converter, typeof(byte[])))
                        {
                            value = converter.ConvertFrom(data);
                            return true;
                        }
                        else
                        {
                            BinaryFormatter formatter = new BinaryFormatter();
                            MemoryStream stream = new MemoryStream(data);

                            value = formatter.Deserialize(stream);
                            return true;
                        }
                    }

                    else
                    {
                        value = null;
                        return false;
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                value = null;
                return false;
            }
        }
Exemplo n.º 19
0
		protected virtual object GetFormattedValue (object value, int rowIndex, ref DataGridViewCellStyle cellStyle, TypeConverter valueTypeConverter, TypeConverter formattedValueTypeConverter, DataGridViewDataErrorContexts context)
		{
			if (DataGridView == null)
				return null;
				
			if (rowIndex < 0 || rowIndex >= DataGridView.RowCount)
				throw new ArgumentOutOfRangeException ("rowIndex");

			// Give the user a chance to custom format
			if (!(this is DataGridViewRowHeaderCell)) {
				DataGridViewCellFormattingEventArgs e = new DataGridViewCellFormattingEventArgs (ColumnIndex, rowIndex, value, FormattedValueType, cellStyle);
				DataGridView.OnCellFormattingInternal (e);
			
				if (e.FormattingApplied)
					return e.Value;
			
				cellStyle = e.CellStyle;
				value = e.Value;
			}
			
			if (value == null || (cellStyle != null && value == cellStyle.DataSourceNullValue)) {
				if (FormattedValueType == typeof (string))
					return String.Empty;
			}

			if (FormattedValueType == typeof(string) && value is IFormattable && !String.IsNullOrEmpty (cellStyle.Format))
				return ((IFormattable) value).ToString (cellStyle.Format, cellStyle.FormatProvider);
			if (value != null && FormattedValueType.IsAssignableFrom (value.GetType()))
				return value;

			if (formattedValueTypeConverter == null)
				formattedValueTypeConverter = FormattedValueTypeConverter;
			if (valueTypeConverter == null)
				valueTypeConverter = ValueTypeConverter;

			if (valueTypeConverter != null && valueTypeConverter.CanConvertTo (FormattedValueType))
				return valueTypeConverter.ConvertTo (value, FormattedValueType);
			if (formattedValueTypeConverter != null && formattedValueTypeConverter.CanConvertFrom (ValueType))
				return formattedValueTypeConverter.ConvertFrom (value);

			return Convert.ChangeType (value, FormattedValueType);
		}
Exemplo n.º 20
0
        protected virtual void SetHighlightValue(FrameworkElement ctrl, DependencyProperty dpProp, Highlight h, HighlightConverter converter, TypeConverter finalConverter)
        {
            if (converter == null) throw new ArgumentNullException("converter");
            if (finalConverter == null) throw new ArgumentNullException("finalConverter");

            var value = converter.Convert(h, null, null, null);
            if (value == Binding.DoNothing)
                ctrl.SetValue(dpProp, DependencyProperty.UnsetValue);
            else if (value == null)
                ctrl.SetValue(dpProp, null);
            else if (dpProp.PropertyType.IsAssignableFrom(value.GetType()))
                ctrl.SetValue(dpProp, value);
            else
                ctrl.SetValue(dpProp, finalConverter.ConvertFrom(value));
        }
Exemplo n.º 21
0
        /// <devdoc>
        ///
        /// Converts a value into a format suitable for display to the end user.
        ///
        /// - Converts DBNull or null into a suitable formatted representation of 'null'
        /// - Performs some special-case conversions (eg. Boolean to CheckState)
        /// - Uses TypeConverters or IConvertible where appropriate
        /// - Throws a FormatException is no suitable conversion can be found
        ///
        /// </devdoc>
        private static object FormatObjectInternal(object value,
                                                   Type targetType, 
                                                   TypeConverter sourceConverter, 
                                                   TypeConverter targetConverter, 
                                                   string formatString, 
                                                   IFormatProvider formatInfo, 
                                                   object formattedNullValue) {
            if (value == System.DBNull.Value || value == null) {
                //
                // Convert DBNull to the formatted representation of 'null' (if possible)
                //
                if (formattedNullValue != null)
                {
                    return formattedNullValue;
                }

                //
                // Convert DBNull or null to a specific 'known' representation of null (otherwise fail)
                //
                if (targetType == stringType)
                {
                    return String.Empty;
                }
                
                if (targetType == checkStateType) {
                    return CheckState.Indeterminate;
                }
                
                // Just pass null through: if this is a value type, it's been unwrapped here, so we return null 
                // and the caller has to wrap if appropriate.
                return null; 
            }

            //
            // Special case conversions
            //

            if (targetType == stringType) {
                if (value is IFormattable && !String.IsNullOrEmpty(formatString)) {
                    return (value as IFormattable).ToString(formatString, formatInfo);
                }
            }

            //The converters for properties should take precedence.  Unfortunately, we don't know whether we have one.  Check vs. the 
            //type's TypeConverter.  We're punting the case where the property-provided converter is the same as the type's converter.
            Type sourceType = value.GetType();
            TypeConverter sourceTypeTypeConverter = TypeDescriptor.GetConverter(sourceType);
            if (sourceConverter != null && sourceConverter != sourceTypeTypeConverter && sourceConverter.CanConvertTo(targetType)) {
                return sourceConverter.ConvertTo(null, GetFormatterCulture(formatInfo), value, targetType);
            }

            TypeConverter targetTypeTypeConverter = TypeDescriptor.GetConverter(targetType);
            if (targetConverter != null && targetConverter != targetTypeTypeConverter && targetConverter.CanConvertFrom(sourceType)) {
                return targetConverter.ConvertFrom(null, GetFormatterCulture(formatInfo), value);
            }

            if (targetType == checkStateType) {
                if (sourceType == booleanType) {
                    return ((bool)value) ? CheckState.Checked : CheckState.Unchecked;
                } 
                else {
                    if (sourceConverter == null) {
                        sourceConverter = sourceTypeTypeConverter;
                    }
                    if (sourceConverter != null && sourceConverter.CanConvertTo(booleanType)) {
                        return (bool)sourceConverter.ConvertTo(null, GetFormatterCulture(formatInfo), value, booleanType)
                            ? CheckState.Checked : CheckState.Unchecked;
                    }
                }
            }

            if (targetType.IsAssignableFrom(sourceType)) {
                return value;
            }

            //
            // If explicit type converters not provided, supply default ones instead
            //

            if (sourceConverter == null) {
                sourceConverter = sourceTypeTypeConverter;
            }

            if (targetConverter == null) {
                targetConverter = targetTypeTypeConverter;
            }

            //
            // Standardized conversions
            //

            if (sourceConverter != null && sourceConverter.CanConvertTo(targetType)) {
                return sourceConverter.ConvertTo(null, GetFormatterCulture(formatInfo), value, targetType);
            }
            else if (targetConverter != null && targetConverter.CanConvertFrom(sourceType)) {
                return targetConverter.ConvertFrom(null, GetFormatterCulture(formatInfo), value);
            }
            else if (value is IConvertible) {
                return ChangeType(value, targetType, formatInfo);
            }

            //
            // Fail if no suitable conversion found
            //

            throw new FormatException(GetCantConvertMessage(value, targetType));
        }
 private object ConvertType(FieldMap fm, object val)
 {
     Check.VerifyNotNull(fm, Error.NullParameter, "fm");
     // convert DBNull to system null
     if (val != null && val.Equals(DBNull.Value))
     {
         val = null;
     }
     // perform null handling (NullValue translation)
     if (val == null && !fm.IsNullAssignable)
     {
         Check.Verify(fm.NullValue != null, Error.NullWithNoNullValue, fm.ColumnName, fm.Type);
         return(fm.NullValue);
     }
     else
     {
         if (val != null)
         {
             Type type = val.GetType();
             // trim strings.. otherwise char columns are as wide as their size
             if (fm.Type == typeof(string) || fm.Type == typeof(Guid))
             {
                 if (fm.Type == typeof(Guid))
                 {
                     if (fm.Size == 16)                              // binary compressed version
                     {
                         val = Common.TypeConverter.ToGuid((string)val);
                     }
                     else
                     {
                         val = new Guid(val.ToString());
                     }
                 }
                 else
                 {
                     string strval = (string)val;
                     // size is 0 for variable width columns
                     // assume we should trim all fixed-width columns
                     val = fm.Size > 0 ? strval.TrimEnd() : strval;
                 }
             }
             else if (fm.Type == typeof(bool) && type != typeof(bool))
             {
                 // if property is boolean but database uses integers we need to convert
                 // the type before updating it
                 val = Convert.ToBoolean(val);
             }
             else if (fm.Type.IsEnum && !type.IsEnum)
             {
                 // check whether enum should be stored as string or numeric value
                 // TODO we should check if enum requires 64-bit conversion
                 // val = fm.HandleEnumAsString ? Enum.Parse( fm.Type, Convert.ToString( val ), true ) : Enum.ToObject( fm.Type, Convert.ToInt32( val ) );
                 val = Common.TypeConverter.Get(fm.Type, val);
             }
             else if (fm.Type == typeof(decimal) && type != typeof(decimal))
             {
                 val = Convert.ToDecimal(val, NumberFormatInfo.InvariantInfo);
             }
             else if (fm.Type != type)
             {
                 TypeConverter typeConv = TypeDescriptor.GetConverter(fm.Type);
                 if (typeConv != null && typeConv.CanConvertFrom(type))
                 {
                     val = typeConv.ConvertFrom(val);
                 }
                 else
                 {
                     // check for the existence of a TypeConverterAttribute for the field/property
                     object[] attrs = fm.MemberInfo.GetCustomAttributes(typeof(TypeConverterAttribute), false);
                     if (attrs.Length == 1)
                     {
                         TypeConverterAttribute tca           = (TypeConverterAttribute)attrs[0];
                         TypeConverter          typeConverter = (TypeConverter)
                                                                Activator.CreateInstance(Type.GetType(tca.ConverterTypeName));
                         if (typeConverter != null && typeConverter.CanConvertFrom(val.GetType()))
                         {
                             val = typeConverter.ConvertFrom(val);
                         }
                         else
                         {
                             val = Convert.ChangeType(val, fm.Type);
                         }
                     }
                     else
                     {
                         val = Convert.ChangeType(val, fm.Type);
                     }
                 }
             }
         }
         else
         {
             // allow NullValue conversion for null strings
             if (fm.Type == typeof(string) && fm.NullValue != null)
             {
                 val = fm.NullValue;
             }
         }
         return(val);
     }
 }
Exemplo n.º 23
0
			protected override object Read (byte token, BinaryReader r, ReaderContext ctx)
			{
				Type t = (Type) ObjectFormatter.ReadObject (r, ctx);
				converter = TypeDescriptor.GetConverter (t);
				token = r.ReadByte ();
				string v = (string) base.Read (token, r, ctx);
				return converter.ConvertFrom (null, Helpers.InvariantCulture, v);
			}
        public static object ChangeType(object value, Type destinationType, CultureInfo culture)
        {
            if (value == null || value.IsDbNull())
            {
                return((!destinationType.IsValueType()) ? null : Activator.CreateInstance(destinationType));
            }
            Type type = value.GetType();

            if (destinationType == type || destinationType.IsAssignableFrom(type))
            {
                return(value);
            }
            if (destinationType.IsGenericType())
            {
                Type genericTypeDefinition = destinationType.GetGenericTypeDefinition();
                if (genericTypeDefinition == typeof(Nullable <>))
                {
                    Type   destinationType2 = destinationType.GetGenericArguments()[0];
                    object obj = ChangeType(value, destinationType2, culture);
                    return(Activator.CreateInstance(destinationType, obj));
                }
            }
            if (destinationType.IsEnum())
            {
                string text = value as string;
                return((text == null) ? value : Enum.Parse(destinationType, text, true));
            }
            if (destinationType == typeof(bool))
            {
                if ("0".Equals(value))
                {
                    return(false);
                }
                if ("1".Equals(value))
                {
                    return(true);
                }
            }
            System.ComponentModel.TypeConverter converter = TypeDescriptor.GetConverter(type);
            if (converter != null && converter.CanConvertTo(destinationType))
            {
                return(converter.ConvertTo(null, culture, value, destinationType));
            }
            System.ComponentModel.TypeConverter converter2 = TypeDescriptor.GetConverter(destinationType);
            if (converter2 != null && converter2.CanConvertFrom(type))
            {
                return(converter2.ConvertFrom(null, culture, value));
            }
            Type[] array = new Type[2]
            {
                type,
                destinationType
            };
            foreach (Type type2 in array)
            {
                foreach (MethodInfo publicStaticMethod2 in type2.GetPublicStaticMethods())
                {
                    if (publicStaticMethod2.IsSpecialName && (publicStaticMethod2.Name == "op_Implicit" || publicStaticMethod2.Name == "op_Explicit") && destinationType.IsAssignableFrom(publicStaticMethod2.ReturnParameter.ParameterType))
                    {
                        ParameterInfo[] parameters = publicStaticMethod2.GetParameters();
                        if (parameters.Length == 1 && parameters[0].ParameterType.IsAssignableFrom(type))
                        {
                            try
                            {
                                return(publicStaticMethod2.Invoke(null, new object[1]
                                {
                                    value
                                }));
                            }
                            catch (TargetInvocationException ex)
                            {
                                throw ex.Unwrap();
                            }
                        }
                    }
                }
            }
            if (type == typeof(string))
            {
                try
                {
                    MethodInfo publicStaticMethod = destinationType.GetPublicStaticMethod("Parse", typeof(string), typeof(IFormatProvider));
                    if (publicStaticMethod != null)
                    {
                        return(publicStaticMethod.Invoke(null, new object[2]
                        {
                            value,
                            culture
                        }));
                    }
                    publicStaticMethod = ReflectionExtensions.GetPublicStaticMethod(destinationType, "Parse", typeof(string));
                    if (publicStaticMethod != null)
                    {
                        return(publicStaticMethod.Invoke(null, new object[1]
                        {
                            value
                        }));
                    }
                }
                catch (TargetInvocationException ex2)
                {
                    throw ex2.Unwrap();
                }
            }
            if (destinationType == typeof(TimeSpan))
            {
                return(TimeSpan.Parse((string)ChangeType(value, typeof(string), CultureInfo.InvariantCulture)));
            }
            return(Convert.ChangeType(value, destinationType, CultureInfo.InvariantCulture));
        }
      private static bool TryConvertTo( object value, Type targetType, CultureInfo culture, TypeConverter converter, out object result )
      {
        if( converter != null )
        {
          try
          {
            result = converter.ConvertTo( null, culture, value, targetType );
            return true;
          }
          catch
          {
            // We'll try to convert the value another way.
          }

          if( ( value != null ) && ( converter.CanConvertFrom( value.GetType() ) ) )
          {
            try
            {
              var newValue = converter.ConvertFrom( null, culture, value );
              result = converter.ConvertTo( null, culture, newValue, targetType );

              return true;
            }
            catch
            {
            }
          }
        }

        result = null;
        return false;
      }
Exemplo n.º 26
0
 /// <summary>
 /// Convert the object value using a specified TypeConveter, circumventing the Type's TypeConverter
 /// </summary>
 /// <param name="value">The original object to convert from</param>
 /// <param name="tc">The type converter that will be used</param>
 /// <returns></returns>
 public static object ConvertValueToTargetType(object value, System.ComponentModel.TypeConverter tc)
 {
     //System.ComponentModel.TypeConverter tc = TypeDescriptor.GetConverter(t);
     return(tc.ConvertFrom(value));
 }
Exemplo n.º 27
0
		/// Generic function to read an object value.  Returns true if the read
		/// succeeded.
		private bool ReadValue(XmlNode node, TypeConverter converter, ArrayList errors, out object value)
		{
			try
			{
				foreach (XmlNode child in node.ChildNodes)
				{
					if (child.NodeType == XmlNodeType.Text)
					{
						value = converter.ConvertFromInvariantString(node.InnerText);
						return true;
					}
					else if (child.Name.Equals("Binary"))
					{
						byte[] data = Convert.FromBase64String(child.InnerText);

						// Binary blob.  Now, check to see if the type converter
						// can convert it.  If not, use serialization.
						//
						if (GetConversionSupported(converter, typeof(byte[])))
						{
							value = converter.ConvertFrom(null, CultureInfo.InvariantCulture, data);
							return true;
						}
						else
						{
							BinaryFormatter formatter = new BinaryFormatter();
							MemoryStream stream = new MemoryStream(data);

							value = formatter.Deserialize(stream);
							return true;
						}
					}
					else if (child.Name.Equals("InstanceDescriptor"))
					{
						value = ReadInstanceDescriptor(child, errors);
						return (value != null);
					}
					else
					{
						errors.Add(string.Format("Unexpected element type {0}", child.Name));
						value = null;
						return false;
					}
				}

				// If we get here, it is because there were no nodes.  No nodes and no inner
				// text is how we signify null.
				//
				value = null;
				return true;
			}
			catch (Exception ex)
			{
				errors.Add(ex.Message);
				value = null;
				return false;
			}
		}
Exemplo n.º 28
0
		/// <summary>
		/// Creates a new instance of the ConfigurationProperty class.
		/// </summary>
		/// <param name="name">The name of the xml entity.</param>
		/// <param name="type">The type of the xml entity.</param>
		/// <param name="defaultValue">The default value of the xml entity.</param>
		/// <param name="converter">The type of the converter to apply.</param>
		/// <param name="validation">The validator to use.</param>
		/// <param name="flags">One of the APXmlPropertyOptions enumeration values.</param>
		/// <param name="description">The description of the xml entity.</param>
		public APXmlProperty(string name, Type type, object defaultValue,
			TypeConverter converter, APValidatorBase validation, APXmlPropertyOptions flags, string description)
		{
			_name = name;

			_converter = converter != null ? converter : TypeDescriptor.GetConverter(type);

			if (defaultValue != null)
			{
				if (defaultValue == NoDefaultValue)
				{
					switch (Type.GetTypeCode(type))
					{
						case TypeCode.Object:
							defaultValue = null;
							break;
						case TypeCode.String:
							defaultValue = String.Empty;
							break;
						default:
							defaultValue = Activator.CreateInstance(type);
							break;
					}
				}
				else
				{
					if (!type.IsAssignableFrom(defaultValue.GetType()))
					{
						if (!_converter.CanConvertFrom(defaultValue.GetType()))
							throw new APXmlException(APResource.GetString(APResource.APXml_DefaultValueTypeError, name, type, defaultValue.GetType()));
						defaultValue = _converter.ConvertFrom(defaultValue);
					}
				}
			}

			_defaultValue = defaultValue;
			_flags = flags;
			_type = type;
			_validation = validation != null ? validation : new DefaultAPValidator();
			_description = description;
		}
Exemplo n.º 29
0
        /// <devdoc>
        ///
        /// Converts a value entered by the end user (through UI) into the corresponding binary value.
        ///
        /// - Converts formatted representations of 'null' into DBNull
        /// - Performs some special-case conversions (eg. CheckState to Boolean)
        /// - Uses TypeConverters or IConvertible where appropriate
        /// - Throws a FormatException is no suitable conversion can be found
        ///
        /// </devdoc>
        private static object ParseObjectInternal(object value, 
                                                  Type targetType, 
                                                  Type sourceType, 
                                                  TypeConverter targetConverter, 
                                                  TypeConverter sourceConverter, 
                                                  IFormatProvider formatInfo, 
                                                  object formattedNullValue) {
            //
            // Convert the formatted representation of 'null' to DBNull (if possible)
            //

            if (EqualsFormattedNullValue(value, formattedNullValue, formatInfo) || value == System.DBNull.Value) {
                return System.DBNull.Value;
            }

            //
            // Special case conversions
            //

            TypeConverter targetTypeTypeConverter = TypeDescriptor.GetConverter(targetType);
            if (targetConverter != null && targetTypeTypeConverter != targetConverter && targetConverter.CanConvertFrom(sourceType)) {
                return targetConverter.ConvertFrom(null, GetFormatterCulture(formatInfo), value);
            }

            TypeConverter sourceTypeTypeConverter = TypeDescriptor.GetConverter(sourceType);
            if (sourceConverter != null && sourceTypeTypeConverter != sourceConverter && sourceConverter.CanConvertTo(targetType)) {
                return sourceConverter.ConvertTo(null, GetFormatterCulture(formatInfo), value, targetType);
            }

            if (value is string) {
                // If target type has a suitable Parse method, use that to parse strings
                object parseResult = InvokeStringParseMethod(value, targetType, formatInfo);
                if (parseResult != parseMethodNotFound) {
                    return parseResult;
                }
            }
            else if (value is CheckState) {
                CheckState state = (CheckState)value;
                if (state == CheckState.Indeterminate) {
                    return DBNull.Value;
                }
                // Explicit conversion from CheckState to Boolean
                if (targetType == booleanType) {
                    return (state == CheckState.Checked);
                }
                if (targetConverter == null) {
                    targetConverter = targetTypeTypeConverter;
                }
                if (targetConverter != null && targetConverter.CanConvertFrom(booleanType)) {
                    return targetConverter.ConvertFrom(null, GetFormatterCulture(formatInfo), state == CheckState.Checked);
                }
            }
            else if (value != null && targetType.IsAssignableFrom(value.GetType())) {
                // If value is already of a compatible type, just go ahead and use it
                return value;
            }

            //
            // If explicit type converters not provided, supply default ones instead
            //

            if (targetConverter == null) {
                targetConverter = targetTypeTypeConverter;
            }

            if (sourceConverter == null) {
                sourceConverter = sourceTypeTypeConverter;
            }

            //
            // Standardized conversions
            //

            if (targetConverter != null && targetConverter.CanConvertFrom(sourceType)) {
                return targetConverter.ConvertFrom(null, GetFormatterCulture(formatInfo), value);
            }
            else if (sourceConverter != null && sourceConverter.CanConvertTo(targetType)) {
                return sourceConverter.ConvertTo(null, GetFormatterCulture(formatInfo), value, targetType);
            }
            else if (value is IConvertible) {
                return ChangeType(value, targetType, formatInfo);
            }

            //
            // Fail if no suitable conversion found
            //

            throw new FormatException(GetCantConvertMessage(value, targetType));
        }
Exemplo n.º 30
0
        public static bool Convert(object val, Type targetType, out object result)
        {
            result = val;
            // Trivial cases
            if (val == null)
            {
                // Cannot convert null to value type
                return(!targetType.IsValueType);
            }
            if (targetType.IsAssignableFrom(val.GetType()))
            {
                return(true);
            }

            // Custom type conversions

            if (_customTypeConverter != null)
            {
                if (_customTypeConverter(val, targetType, out result))
                {
                    return(true);
                }
            }

            // TODO: typeof(Nullable<T>)

            // Built-in type conversions

            if (val.GetType() == typeof(string) && targetType == typeof(Type))
            { // string -> Type
                result = Type.GetType(val.ToString());
                return(result != null);
            }

            // Enumerations
            if (val.GetType() == typeof(string) && targetType.IsEnum)
            { // string -> Enum
                result = Enum.Parse(targetType, (string)val);
                return(true);
            }

            // String target type must be done before enumerations are tried - else, the string will be treated as enumeration
            if (targetType.IsAssignableFrom(typeof(string)))
            { // * -> string
                result = val.ToString();
                return(true);
            }

            // Collection types

            Type enumerableType;
            Type entryType;

            ReflectionHelper.FindImplementedEnumerableType(targetType, out enumerableType, out entryType);

            if (enumerableType != null) // Targets IList, ICollection, IList<>, ICollection<>
            {
                ICollection col;
                if (!ToCollection(val, entryType, out col))
                {
                    return(false);
                }
                List <object> resultList = col.Cast <object>().ToList();
                result = resultList;
                return(true);
            }
            ICollection sourceCol = val as ICollection;

            if (sourceCol != null && sourceCol.Count == 1) // From collection to non-collection target
            {
                // Use the first (single) item of a collection or dictionary
                IEnumerator enumerator = sourceCol.GetEnumerator();
                enumerator.MoveNext();
                object item = enumerator.Current;
                if (Convert(item, targetType, out result)) // Single collection item
                {
                    return(true);
                }
                KeyValuePair <object, object>?kvp = item as KeyValuePair <object, object>?;
                if (kvp.HasValue && Convert(kvp.Value.Value, targetType, out result)) // Value of single dictionary entry - generic dictionary
                {
                    IDisposable d = kvp.Value.Key as IDisposable;
                    if (d != null)
                    {
                        d.Dispose();
                    }
                    return(true);
                }
                DictionaryEntry?entry = item as DictionaryEntry?;
                if (entry.HasValue && Convert(entry.Value.Value, targetType, out result)) // Value of single dictionary entry - legacy dictionary
                {
                    IDisposable d = entry.Value.Key as IDisposable;
                    if (d != null)
                    {
                        d.Dispose();
                    }
                    return(true);
                }
            }

            // Simple type conversions

            System.ComponentModel.TypeConverter tc = TypeDescriptor.GetConverter(targetType);
            if (tc != null && tc.CanConvertFrom(val.GetType()))
            {
                try
                {
                    result = tc.ConvertFrom(null, CultureInfo.InvariantCulture, val);
                    return(true);
                }
                catch { }
            }

            tc = TypeDescriptor.GetConverter(val);
            if (tc != null && tc.CanConvertTo(targetType))
            {
                result = tc.ConvertTo(val, targetType);
                return(true);
            }

            return(false);
        }
Exemplo n.º 31
0
 public override object ConvertFrom(cm.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
 {
     return(etoConverter.ConvertFrom(null, culture, value));
 }
Exemplo n.º 32
0
        public bool LoadZip(string ZipPath, List <string> crFiles, Color Transparency)
        {
            if (!File.Exists(ZipPath))
            {
                MessageBox.Show("Unable to load " + ZipPath + ", doesn't exist.", "Mapper", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(false);
            }

            var zip = ZipStorer.Open(ZipPath, FileAccess.Read);

            if (zip == null)
            {
                MessageBox.Show("Unable to load " + ZipPath + ".", "Mapper", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(false);
            }

            var patternToCheck = new List <string>();

            foreach (var cr in crFiles)
            {
                patternToCheck.Add(cr);
            }
            foreach (var path in this.EditorData.GraphicsPaths)
            {
                patternToCheck.Add(path);
            }

            var filesToLoad = new List <ZipStorer.ZipFileEntry>();

            var entries = zip.ReadCentralDir();

            foreach (var entry in entries)
            {
                foreach (var path in patternToCheck)
                {
                    if (!entry.FilenameInZip.Replace('/', '\\').Contains(path))
                    {
                        continue;
                    }
                    if (entry.CompressedSize == 0)
                    {
                        continue;
                    }

                    string filename = entry.FilenameInZip.ToLower().Replace('/', '\\');
                    string ext      = Path.GetExtension(filename).ToLower();

                    if (!(ext == ".frm" || ext == ".png"))
                    {
                        continue;
                    }

                    filesToLoad.Add(entry);
                }
            }

            this.BeginInvoke((MethodInvoker) delegate
            {
                frmLoading.SetNextFile(Path.GetFileName(ZipPath));
                frmLoading.SetResourceNum(filesToLoad.Count);
            });

            foreach (var entry in filesToLoad)
            {
                string filename = entry.FilenameInZip.ToLower().Replace('/', '\\');
                string ext      = Path.GetExtension(filename).ToLower();

                this.BeginInvoke((MethodInvoker) delegate
                {
                    frmLoading.SetNextResource(filename);
                });

                byte[] bytes;
                using (MemoryStream stream = new MemoryStream())
                {
                    zip.ExtractFile(entry, stream);
                    bytes = stream.ToArray();
                }
                if (ext == ".frm")
                {
                    var frm = FalloutFRMLoader.LoadFRM(bytes, Transparency);
                    Frms[filename] = frm;
                }
                else
                {
                    System.ComponentModel.TypeConverter tc = System.ComponentModel.TypeDescriptor.GetConverter(typeof(Bitmap));
                    Bitmap bitmap = (Bitmap)tc.ConvertFrom(bytes);
                    Frms[filename]        = new FalloutFRM();
                    Frms[filename].Frames = new List <Bitmap>();
                    Frms[filename].Frames.Add(bitmap);
                    Frms[filename].FileName = entry.FilenameInZip;
                }
            }
            return(true);
        }
Exemplo n.º 33
0
		public void CheckConversion(object check, object expect, TypeConverter conv, Type type, bool test_from, bool test_to, CultureInfo culture) {
			object obj;
			object result;

			obj = check;

			if (debug > 0) {
				Console.WriteLine("{0}: CheckConversion, checking {1}({2}) <-> {3}({4})", conv.ToString(), check.GetType().ToString(), check.ToString(), type.ToString(), expect != null ? expect.ToString() : "null");
			}

			if (test_to) {
				obj = conv.ConvertTo(null, culture, check, type);

				if (obj == null) {
					if (expect != null) {
						failed++;
						Console.WriteLine("{0}: ConvertTo failed, type {1}, expected {2}, got null", conv.ToString(), type.ToString(), expect.ToString());
					}
					return;
				}

				// Intermediate verification
				if (expect != null && !obj.Equals(expect)) {
					failed++;
					if (verbose > 0) {
						Console.WriteLine("{0}: ConvertTo failed, type {1}, expected {2}, got {3}", conv.ToString(), type.ToString(), expect.ToString(), obj.ToString());
					}
				}

				if (debug > 1) {
					Console.WriteLine("{0}: CheckConversion, ConvertTo result: '{1}')", conv.ToString(), obj);
				}
			}


			if (test_from) {
				result = conv.ConvertFrom(null, culture, obj);

				if (test_to) {
					// Roundtrip check
					if (!check.Equals(result)) {
						failed++;
						if (verbose > 0) {
							Console.WriteLine("{0}: ConvertTo/ConvertFrom roundtrip failed, type {1}", conv.ToString(), type.ToString());
						}
					}

				} else {
					if (!expect.Equals(result)) {
						failed++;
						if (verbose > 0) {
							Console.WriteLine("{0}: ConvertFrom failed, type {1}", conv.ToString(), type.ToString());
						}
					}
				}

				if (debug > 1) {
					Console.WriteLine("{0}: CheckConversion, ConvertFrom result: '{1}')", conv.ToString(), result);
				}
			}
		}
Exemplo n.º 34
0
 private static bool ConvertObjectToTypeInternal(object o, Type type, JavaScriptSerializer serializer, bool throwOnError, out object convertedObject)
 {
     IDictionary<string, object> dictionary = o as IDictionary<string, object>;
     if (dictionary != null)
     {
         return ConvertDictionaryToObject(dictionary, type, serializer, throwOnError, out convertedObject);
     }
     IList list = o as IList;
     if (list != null)
     {
         IList list2;
         if (ConvertListToObject(list, type, serializer, throwOnError, out list2))
         {
             convertedObject = list2;
             return true;
         }
         convertedObject = null;
         return false;
     }
     if ((type == null) || (o.GetType() == type))
     {
         convertedObject = o;
         return true;
     }
     //TypeDescriptor.GetConverter(type) !!!
     TypeConverter converter = new TypeConverter();
     if (converter.CanConvertFrom(o.GetType()))
     {
         try
         {
             convertedObject = converter.ConvertFrom(null, CultureInfo.InvariantCulture, o);
             return true;
         }
         catch
         {
             if (throwOnError)
             {
                 throw;
             }
             convertedObject = null;
             return false;
         }
     }
     if (converter.CanConvertFrom(typeof(string)))
     {
         try
         {
             string str;
             if (o is DateTime)
             {
                 DateTime time = (DateTime)o;
                 str = time.ToUniversalTime().ToString("u", CultureInfo.InvariantCulture);
             }
             else
             {
                 //ConvertToInvariantString(o); !!!
                 str = converter.ConvertToString(o);
             }
             //ConvertFromInvariantString(str); !!!
             convertedObject = converter.ConvertToString(str);
             return true;
         }
         catch
         {
             if (throwOnError)
             {
                 throw;
             }
             convertedObject = null;
             return false;
         }
     }
     if (type.IsAssignableFrom(o.GetType()))
     {
         convertedObject = o;
         return true;
     }
     if (throwOnError)
     {
         throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, AtlasWeb.JSON_CannotConvertObjectToType, new object[] { o.GetType(), type }));
     }
     convertedObject = null;
     return false;
 }
Exemplo n.º 35
0
		public virtual object ParseFormattedValue (object formattedValue, DataGridViewCellStyle cellStyle, TypeConverter formattedValueTypeConverter, TypeConverter valueTypeConverter)
		{
			if (cellStyle == null)
				throw new ArgumentNullException ("cellStyle is null.");
			if (FormattedValueType == null)
				throw new FormatException ("The System.Windows.Forms.DataGridViewCell.FormattedValueType property value is null.");
			if (formattedValue == null)
				throw new ArgumentException ("formattedValue is null.");
			if (ValueType == null)
				throw new FormatException ("valuetype is null");
			if (!FormattedValueType.IsAssignableFrom (formattedValue.GetType ()))
				throw new ArgumentException ("formattedValue is not of formattedValueType.");
			
			if (formattedValueTypeConverter == null)
				formattedValueTypeConverter = FormattedValueTypeConverter;
			if (valueTypeConverter == null)
				valueTypeConverter = ValueTypeConverter;

			if (valueTypeConverter != null && valueTypeConverter.CanConvertFrom (FormattedValueType))
				return valueTypeConverter.ConvertFrom (formattedValue);
			if (formattedValueTypeConverter != null && formattedValueTypeConverter.CanConvertTo (ValueType))
				return formattedValueTypeConverter.ConvertTo (formattedValue, ValueType);
			return Convert.ChangeType (formattedValue, ValueType);
		}
        /// <summary>
        /// ��ȡ"Value"�ڵ�
        /// �������ԣ��������ĵ��е�����ֵ�������͵�ת����ת��Ϊ��ǰ���Ե�ֵ����
        /// </summary>
        /// <param name="node">���ڵ�</param>
        /// <param name="converter">���͵�ת����</param>
        /// <param name="errors">�����ڼ������Ĵ�������еĻ����ļ���</param>
        /// <param name="value">����</param>
        /// <returns>��ֵ�Ƿ��ܹ���ת������Ҫ������</returns>
        private bool ReadValue(XmlNode node, TypeConverter converter, ArrayList errors, ref object value)
        {
            try
            {
                foreach (XmlNode child in node.ChildNodes)
                {
                    //XmlNodeTypeö��ָ���ڵ�����͡�.Text:�ڵ���ı����ݡ�Text �ڵ㲻�ܾ����κ��ӽڵ㡣
                    if (child.NodeType == XmlNodeType.Text)
                    {
                        value = converter.ConvertFromInvariantString(node.InnerText);
                        return true;
                    }
                    else if (child.Name.Equals("Binary"))
                    {
                        byte[] data = Convert.FromBase64String(child.InnerText);

                        if (GetConversionSupported(converter, typeof(byte[])))
                        {
                            value = converter.ConvertFrom(data);
                            return true;
                        }
                        else
                        {
                            BinaryFormatter formatter = new BinaryFormatter();
                            MemoryStream stream = new MemoryStream(data);

                            value = formatter.Deserialize(stream);
                            return true;
                        }
                    }

                    else
                    {
                        errors.Add(string.Format("��������{0}", child.Name));
                        value = null;
                        return false;
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                value = null;
                return false;
            }
        }
Exemplo n.º 37
0
 public static object ChangeType(Type t, object value)
 {
     System.ComponentModel.TypeConverter tc = System.ComponentModel.TypeDescriptor.GetConverter(t);
     return(tc.ConvertFrom(value));
 }
Exemplo n.º 38
0
        public bool LoadDat(string DatPath, List <string> crFiles, Color Transparency)
        {
            DatReaderError status;
            DAT            loadedDat = DATReader.ReadDat(DatPath, out status);

            if (status.Error != DatError.Success)
            {
                MessageBox.Show("Error loading " + DatPath + ": " + Environment.NewLine + status.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(false);
            }

            List <DATFile> files = new List <DATFile>();

            foreach (string path in this.EditorData.GraphicsPaths)
            {
                files.AddRange(loadedDat.GetFilesByPattern(path));

                // Critters to load
                foreach (var crType in critterData.crTypeGraphic.Values)
                {
                    var file = loadedDat.GetFileByName("art\\critters\\" + crType.ToUpper() + "AA.FRM"); // Idle anim
                    if (file == null)
                    {
                        file = loadedDat.GetFileByName("art\\critters\\" + crType.ToLower() + "aa.frm");
                    }
                    if (file == null)
                    {
                        continue;
                    }
                    files.Add(file);
                }
            }

            this.BeginInvoke((MethodInvoker) delegate {
                frmLoading.SetNextFile(Path.GetFileName(DatPath));
                frmLoading.SetResourceNum(files.Count);
            });

            foreach (DATFile file in files)
            {
                this.BeginInvoke((MethodInvoker) delegate { frmLoading.SetNextResource(file.FileName); });

                string ext = Path.GetExtension(file.FileName).ToLower();
                if (!(ext == ".frm" || ext == ".png"))
                {
                    continue;
                }

                byte[] data = file.GetData();
                if (data == null)
                {
                    WriteLog("Error opening " + file.FileName + ": " + file.ErrorMsg);
                    continue;
                }

                if (ext == ".frm")
                {
                    var frm = FalloutFRMLoader.LoadFRM(data, Transparency);
                    frm.FileName       = file.Path.ToLower();
                    Frms[frm.FileName] = frm;
                }
                else
                {
                    System.ComponentModel.TypeConverter tc = System.ComponentModel.TypeDescriptor.GetConverter(typeof(Bitmap));
                    Bitmap bitmap = (Bitmap)tc.ConvertFrom(data);
                }
            }
            loadedDat.Close();
            return(true);
        }
 private bool ReadValue(XmlNode node, TypeConverter converter, ArrayList errors, out object value)
 {
     try
     {
         foreach (XmlNode child in node.ChildNodes)
         {
             if (child.NodeType == XmlNodeType.Text)
             {
                 value = converter.ConvertFromInvariantString(node.InnerText);
                 return true;
             }
             if (child.Name.Equals("Binary"))
             {
                 byte[] data = Convert.FromBase64String(child.InnerText);
                 if (this.GetConversionSupported(converter, typeof(byte[])))
                 {
                     value = converter.ConvertFrom(null, CultureInfo.InvariantCulture, data);
                     return true;
                 }
                 BinaryFormatter formatter = new BinaryFormatter();
                 MemoryStream stream = new MemoryStream(data);
                 value = formatter.Deserialize(stream);
                 return true;
             }
             if (child.Name.Equals("InstanceDescriptor"))
             {
                 value = this.ReadInstanceDescriptor(child, errors);
                 return (value != null);
             }
             errors.Add(string.Format("Unexpected element type {0}", child.Name));
             value = null;
             return false;
         }
         value = null;
         return true;
     }
     catch (Exception ex)
     {
         errors.Add(ex.Message);
         value = null;
         return false;
     }
 }
Exemplo n.º 40
0
        /// <summary>
        /// Converts the given object to the type of this converter, using the specified
        /// context and culture information.
        /// </summary>
        /// <param name="context">An System.ComponentModel.ITypeDescriptorContext that provides a format context.</param>
        /// <param name="culture">The System.Globalization.CultureInfo to use as the current culture.</param>
        /// <param name="value">The System.Object to convert.</param>
        /// <returns>An System.Object that represents the converted value.</returns>
        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            TypeConverter converter = TypeDescriptor.GetConverter(typeof(double));

            return(converter.ConvertFrom(context, culture, value));
        }