예제 #1
0
        /// <summary>
        /// Load settings
        /// </summary>
        /// <param name="type">Type</param>
        /// <param name="storeId">Store identifier for which settings should be loaded</param>
        public virtual ISettings LoadSetting(Type type, Guid storeId = default(Guid))
        {
            var settings = Activator.CreateInstance(type);

            foreach (var prop in type.GetProperties())
            {
                // get properties we can read and write to
                if (!prop.CanRead || !prop.CanWrite)
                {
                    continue;
                }

                var key = type.Name + "." + prop.Name;
                //load by store
                var setting = GetSettingByKey <string>(key, storeId: storeId, loadSharedValueIfNotFound: true);
                if (setting == null)
                {
                    continue;
                }

                if (!TypeDescriptor.GetConverter(prop.PropertyType).CanConvertFrom(typeof(string)))
                {
                    continue;
                }

                if (!TypeDescriptor.GetConverter(prop.PropertyType).IsValid(setting))
                {
                    continue;
                }

                var value = TypeDescriptor.GetConverter(prop.PropertyType).ConvertFromInvariantString(setting);

                //set property
                prop.SetValue(settings, value, null);
            }

            return(settings as ISettings);
        }
        public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
        {
            //MessageBox.Show("ConvertFrom\t" + (string)value);
            string text = value as string;

            if (text != null)
            {
                text = text.Trim();

                if (text.Length != 0)
                {
                    if (culture == null)
                    {
                        culture = CultureInfo.CurrentCulture;
                    }

                    char separator = culture.TextInfo.ListSeparator[0];
                    //MessageBox.Show(separator.ToString());
                    string[] textArray = text.Split(separator);
                    int[]    numArray  = new int[textArray.Length];

                    TypeConverter intConverter = TypeDescriptor.GetConverter(typeof(int));
                    for (int i = 0; i < text.Length; i++)
                    {
                        numArray[i] = (int)intConverter.ConvertFromString(context, culture, textArray[i]);
                    }

                    if (numArray.Length != 4)
                    {
                        throw new ArgumentException("Format de chaine incorrect");
                    }

                    return(new Margin(numArray[0], numArray[1], numArray[2], numArray[3]));
                }
                return(null);
            }
            return(base.ConvertFrom(context, culture, value));
        }
예제 #3
0
        /// <summary>
        /// Load settings
        /// </summary>
        /// <typeparam name="T">Type</typeparam>
        public virtual T LoadSetting <T>() where T : ISettings, new()
        {
            var settings = Activator.CreateInstance <T>();

            foreach (var prop in typeof(T).GetProperties())
            {
                // get properties we can read and write to
                if (!prop.CanRead || !prop.CanWrite)
                {
                    continue;
                }

                var key = typeof(T).Name + "." + prop.Name;
                //load by store
                var setting = GetSettingByKey <string>(key);
                if (setting == null)
                {
                    continue;
                }

                if (!TypeDescriptor.GetConverter(prop.PropertyType).CanConvertFrom(typeof(string)))
                {
                    continue;
                }

                if (!TypeDescriptor.GetConverter(prop.PropertyType).IsValid(setting))
                {
                    continue;
                }

                object value = TypeDescriptor.GetConverter(prop.PropertyType).ConvertFromInvariantString(setting);

                //set property
                prop.SetValue(settings, value, null);
            }

            return(settings);
        }
예제 #4
0
        /// <summary>
        ///     Asynchronously executes the binding for the given request.
        /// </summary>
        /// <param name="metadataProvider">Metadata provider to use for validation.</param>
        /// <param name="actionContext">
        ///     The action context for the binding. The action context contains the parameter dictionary
        ///     that will get populated with the parameter.
        /// </param>
        /// <param name="cancellationToken">Cancellation token for cancelling the binding operation.</param>
        /// <returns>A task object representing the asynchronous operation.</returns>
        /// <exception cref="HttpResponseException">
        /// </exception>
        public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider,
                                                 HttpActionContext actionContext, CancellationToken cancellationToken)
        {
            if (actionContext.Request.Headers.TryGetValues(_name, out var values))
            {
                var converter = TypeDescriptor.GetConverter(Descriptor.ParameterType);
                try
                {
                    actionContext.ActionArguments[Descriptor.ParameterName] =
                        converter.ConvertFromString(values.FirstOrDefault());
                }
                catch (Exception exception)
                {
                    var error = new HttpError("The request is invalid.")
                    {
                        MessageDetail = exception.Message
                    };
                    throw new HttpResponseException(
                              actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, error));
                }
            }
            else if (Descriptor.IsOptional)
            {
                actionContext.ActionArguments[Descriptor.ParameterName] =
                    Descriptor.DefaultValue ?? Activator.CreateInstance(Descriptor.ParameterType);
            }
            else
            {
                var error = new HttpError("The request is invalid.")
                {
                    MessageDetail = $"The `{_name}` header is required."
                };
                throw new HttpResponseException(
                          actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, error));
            }

            return(Task.FromResult <object>(null));
        }
        private static IComparable ConvertBound(Type boundType, string bound, string boundParameter)
        {
            if (boundType == null)
            {
                throw new ArgumentNullException("boundType");
            }
            if (!typeof(IComparable).IsAssignableFrom(boundType))
            {
                throw new ArgumentException(Resources.ExceptionBoundTypeNotIComparable, "boundType");
            }
            if (bound == null)
            {
                return(null);
            }
            IComparable result;

            if (boundType == typeof(DateTime))
            {
                try
                {
                    result = DateTime.ParseExact(bound, "s", CultureInfo.InvariantCulture);
                    return(result);
                }
                catch (FormatException innerException)
                {
                    throw new ArgumentException(Resources.ExceptionInvalidDate, boundParameter, innerException);
                }
            }
            try
            {
                result = (IComparable)TypeDescriptor.GetConverter(boundType).ConvertFrom(null, CultureInfo.InvariantCulture, bound);
            }
            catch (Exception innerException2)
            {
                throw new ArgumentException(Resources.ExceptionCannotConvertBound, innerException2);
            }
            return(result);
        }
예제 #6
0
 /// <summary>Converts the specified object to the specified type.</summary>
 /// <returns>The converted object.</returns>
 /// <param name="context">A <see cref="T:System.ComponentModel.ITypeDescriptorContext" /> that can be used to get additional information about the environment this converter is being called from. This may be null, so you should always check. Also, properties on the context object may also return null. </param>
 /// <param name="culture">An <see cref="T:System.Globalization.CultureInfo" /> object that contains culture specific information, such as the language, calendar, and cultural conventions associated with a specific culture. It is based on the RFC 1766 standard. </param>
 /// <param name="value">The object to convert. </param>
 /// <param name="destinationType">The type to convert the object to. </param>
 /// <exception cref="T:System.NotSupportedException">The conversion cannot be completed.</exception>
 /// <filterpriority>1</filterpriority>
 public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
 {
     if (destinationType == null)
     {
         throw new ArgumentNullException("destinationType");
     }
     if (value is AvailableIntRange)
     {
         if (destinationType == typeof(string))
         {
             AvailableIntRange size = (AvailableIntRange)value;
             if (culture == null)
             {
                 culture = CultureInfo.CurrentCulture;
             }
             string        str       = string.Concat(culture.TextInfo.ListSeparator, " ");
             TypeConverter converter = TypeDescriptor.GetConverter(typeof(int));
             string[]      strArrays = new string[2];
             int           num       = 0;
             int           num1      = num + 1;
             strArrays[num] = converter.ConvertToString(context, culture, size.MinimizeValue);
             int num2 = num1;
             num1            = num2 + 1;
             strArrays[num2] = converter.ConvertToString(context, culture, size.MaximizeValue);
             return(string.Join(str, strArrays));
         }
         if (destinationType == typeof(InstanceDescriptor))
         {
             AvailableIntRange size1       = (AvailableIntRange)value;
             ConstructorInfo   constructor = typeof(AvailableIntRange).GetConstructor(new Type[] { typeof(int), typeof(int) });
             if (constructor != null)
             {
                 return(new InstanceDescriptor(constructor, new object[] { size1.MinimizeValue, size1.MaximizeValue }));
             }
         }
     }
     return(base.ConvertTo(context, culture, value, destinationType));
 }
예제 #7
0
        internal static EventDescriptor EventDescriptorFromMetadata(Type t, EventAttribute eAttr)
        {
            var result = new EventDescriptor()
            {
                Name            = eAttr.Name,
                ObjectType      = eAttr.Type,
                Description     = eAttr.Description,
                ExampleLogLines = (from a in t.GetCustomAttributes(typeof(ExampleLineAttribute), true).OfType <ExampleLineAttribute>()
                                   select a.Value).ToList(),
            };

            result.Fields = from f in t.GetFields()
                            from a in f.GetCustomAttributes(typeof(EventFieldAttribute), true).OfType <EventFieldAttribute>()
                            select new EventFieldDescriptor()
            {
                Field             = f,
                Group             = a.From,
                Converter         = TypeDescriptor.GetConverter(f.FieldType),
                FromObjectAddress = a.FromObjectAddress
            };

            return(result);
        }
예제 #8
0
        public static object ConvertValue(object value, Type type)
        {
            if (value == null)
            {
                return(type.IsValueType ? Activator.CreateInstance(type) : null);
            }

            var conv1 = TypeDescriptor.GetConverter(type);

            if (conv1.CanConvertFrom(value.GetType()))
            {
                return(conv1.ConvertFrom(value));
            }

            var conv2 = TypeDescriptor.GetConverter(value.GetType());

            if (conv2.CanConvertTo(type))
            {
                return(conv2.ConvertTo(value, type));
            }

            return(Convert.ChangeType(value, type));
        }
예제 #9
0
        /// <summary>
        /// Returns <see cref="TypeConverter"/> for the specified type.
        /// </summary>
        /// <param name="type">Type to get the converter for.</param>
        /// <returns>a type converter for the specified type.</returns>
        /// <exception cref="ArgumentNullException">If <paramref name="type"/> is <c>null</c>.</exception>
        public static TypeConverter GetConverter(Type type)
        {
            if (type == null)
            {
                throw new ArgumentNullException(nameof(type));
            }

            var converter = (TypeConverter)converters[type];

            if (converter == null)
            {
                if (type.GetTypeInfo().IsEnum)
                {
                    converter = new EnumConverter(type);
                }
                else
                {
                    converter = TypeDescriptor.GetConverter(type);
                }
            }

            return(converter);
        }
        /// <summary>
        /// Creates a data structure of this type from .NET PageSettings.
        /// </summary>
        public static PageSettingsData ToData(this PageSettings source)
        {
            // Validate
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }

            // Convert...
            var target = new PageSettingsData
            {
                Color         = source.Color,
                Landscape     = source.Landscape,
                Margins       = TypeDescriptor.GetConverter(typeof(Margins)).ConvertToInvariantString(source.Margins),
                PaperWidth    = source.PaperSize.Width,
                PaperHeight   = source.PaperSize.Height,
                PaperName     = source.PaperSize.PaperName,
                PaperSizeKind = (int)source.PaperSize.Kind,
                PrinterName   = source.PrinterSettings.PrinterName
            };

            return(target);
        }
예제 #11
0
    /// <summary>
    /// 反射变量赋值
    /// </summary>
    /// <param name="info"></param>
    /// <param name="var"></param>
    /// <param name="value"></param>
    /// <param name="type"></param>
    private static void SetValue(PropertyInfo info, object var, string value, string type)
    {
        object val = (object)value;

        if (type == "int")
        {
            val = System.Convert.ToInt32(val);
        }
        else if (type == "bool")
        {
            val = System.Convert.ToBoolean(val);
        }
        else if (type == "float")
        {
            val = System.Convert.ToSingle(val);
        }
        else if (type == "enum")
        {
            val = TypeDescriptor.GetConverter(info.PropertyType).ConvertFromInvariantString(val.ToString());
        }

        info.SetValue(var, val);
    }
예제 #12
0
 /// <summary>Initializes a new instance of the <see cref="ListViewGroupingSet{T}"/> class.</summary>
 /// <param name="converter">
 /// The converter to take the <typeparamref name="T"/> and convert it to a <see cref="ListViewGroup"/>. If <typeparamref name="T"/>
 /// is not <see cref="ListViewGroup"/>, an exception is thrown.
 /// </param>
 /// <exception cref="System.InvalidCastException">Generic type T must be convertible to a ListViewGroup.</exception>
 public ListViewGroupingSet(Converter <T, ListViewGroup> converter = null)
 {
     if (converter != null)
     {
         this.converter = converter;
     }
     else
     {
         if (typeof(T) == typeof(ListViewGroup))
         {
             this.converter = a => a as ListViewGroup;
         }
         else
         {
             var tc = TypeDescriptor.GetConverter(typeof(T));
             if (!tc.CanConvertTo(typeof(ListViewGroup)))
             {
                 throw new InvalidCastException("Generic type T must be convertible to a ListViewGroup.");
             }
             this.converter = t => (ListViewGroup)tc.ConvertTo(t, typeof(ListViewGroup));
         }
     }
 }
예제 #13
0
        /// <summary>
        /// Returns value from claim converted to T
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="identity"></param>
        /// <param name="claimName"></param>
        /// <returns></returns>
        public static T GetValue <T>(ClaimsIdentity identity, string claimName)
        {
            var claim = identity.FindFirst(x => x.Type == claimName);

            if (claim == null)
            {
                return(default(T));
            }

            if (String.IsNullOrWhiteSpace(claim.Value))
            {
                return(default(T));
            }

            try
            {
                return((T)TypeDescriptor.GetConverter(typeof(T)).ConvertFromInvariantString(claim.Value));
            }
            catch (Exception exception)
            {
                throw new MicroserviceInvalidCastException($"{claim.Value} from {claim.Value} to {typeof(T)}", exception);
            }
        }
예제 #14
0
            public static DesktopWindow FromXmlElement(XmlElement element)
            {
                Platform.CheckTrue(element.Name == "desktop-window", "The settings xml is invalid.");

                string        name          = element.GetAttribute("name");
                TypeConverter converter     = TypeDescriptor.GetConverter(typeof(Rectangle));
                Rectangle     restoreBounds = (Rectangle)converter.ConvertFromInvariantString(element.GetAttribute("bounds"));

                converter = TypeDescriptor.GetConverter(typeof(FormWindowState));
                FormWindowState restoreState = (FormWindowState)converter.ConvertFromInvariantString(element.GetAttribute("state"));

                DesktopWindow window = new DesktopWindow(name);

                window.Bounds = restoreBounds;
                window.State  = restoreState;

                foreach (XmlElement shelf in element["shelves"].ChildNodes)
                {
                    window._shelves.Add(Shelf.FromXmlElement(shelf));
                }

                return(window);
            }
예제 #15
0
        public bool TryLoad <T>(string db_path, string group, string parameter, out T value)
        {
            // https://stackoverflow.com/questions/2961656/generic-tryparse
            string value_str = this.Load(db_path, group, parameter);

            try
            {
                var converter = TypeDescriptor.GetConverter(typeof(T));
                if (converter != null)
                {
                    // Cast ConvertFromString(string text) : object to (T)
                    value = (T)converter.ConvertFromString(value_str);
                    return(true);
                }
                value = default(T);
                return(false);
            }
            catch (Exception)
            {
                value = default(T);
                return(false);
            }
        }
    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        try
        {
            int         index = e.RowIndex;
            GridViewRow row   = GridView1.Rows[index];

            ProductBrandInfoDTO pbDto = new ProductBrandInfoDTO();

            DataKey dk = GridView1.DataKeys[index];
            this.hfPrimaryKey.Value = dk.Value.ToString();
            pbDto.PrimaryKey        = (Guid)TypeDescriptor.GetConverter(pbDto.PrimaryKey).ConvertFromString(this.hfPrimaryKey.Value);

            IProductBrandBL pbFacade = Facade.GetInstance().GetPBBlImp();
            pbFacade.DelProductBrand(pbDto);
            this.hfPrimaryKey.Value = "";
            GridView1.DataBind();
        }
        catch (Exception Exp)
        {
            lblErrorMessage.Text = cls.ErrorString(Exp);
        }
    }
예제 #17
0
        protected virtual DataGridViewColumn CreateDefaultColumn(PropertyDescriptor propertyDescriptor)
        {
            DataGridViewColumn dataGridViewColumn;
            var type = propertyDescriptor.PropertyType;

            if (type == typeof(bool) || type == typeof(CheckState))
            {
                dataGridViewColumn = new DataGridViewCheckBoxColumn(type == typeof(CheckState));
            }
            else
            {
                TypeConverter converter = TypeDescriptor.GetConverter(typeof(Image));
                if (typeof(Image).IsAssignableFrom(type) || converter.CanConvertFrom(type))
                {
                    dataGridViewColumn = new DataGridViewImageColumn();
                }
                else
                {
                    dataGridViewColumn = new DataGridViewTextBoxColumn();
                }
            }
            return(dataGridViewColumn);
        }
예제 #18
0
        private Expression c1(Expression left, Expression right)
        {
            if (left.Type == right.Type)
            {
                return(left);
            }
            var cvt = TypeDescriptor.GetConverter(left.Type);

            if (cvt.CanConvertTo(right.Type))
            {
                return(Expression.Convert(left, right.Type));
            }
            else
            {
                Tuple <MethodInfo, object> mi;
                if (dico.TryGetValue(new Tuple <Type, Type>(left.Type, right.Type), out mi))
                {
                    return(Expression.Call(Expression.Constant(mi.Item2), mi.Item1, left));
                }
                // we will try to convert right to left in c2 function
                return(left);
            }
        }
예제 #19
0
        public object ConvertObject(object obj)
        {
            if (obj == null)
            {
                return(NullValues[FieldTypeIndex]);
            }

            Type typ = obj.GetType();

            if (typ == fieldType)
            {
                return(obj);
            }

            TypeConverter typeConverter = TypeDescriptor.GetConverter(fieldType);

            if (typeConverter.CanConvertFrom(typ))
            {
                return(typeConverter.ConvertFrom(obj));
            }

            return(DefaultValue);
        }
예제 #20
0
        public override void WriteXml(XmlWriter writer)
        {
            TypeConverter cc = TypeDescriptor.GetConverter(typeof(Color));
            TypeConverter bc = TypeDescriptor.GetConverter(typeof(bool));

            base.WriteXml(writer);

            writer.WriteElementString("Orientation", Orientation.ToString());
            writer.WriteElementString("AlwaysOnTop", bc.ConvertToInvariantString(AlwaysOnTop));

            writer.WriteStartElement("Background");
            if (!string.IsNullOrWhiteSpace(BackgroundImage))
            {
                writer.WriteElementString("Image", BackgroundImage);
                writer.WriteElementString("ImageAlignment", BackgroundAlignment.ToString());
            }

            if (FillBackground)
            {
                writer.WriteElementString("Color", cc.ConvertToInvariantString(BackgroundColor));
            }
            writer.WriteEndElement();
        }
        public object?ConvertToDesiredType(object?evaluationResult, Type desiredType)
        {
            if (desiredType == typeof(object))
            {
                return(evaluationResult);
            }

            var converter = TypeDescriptor.GetConverter(evaluationResult !);

            if (converter.CanConvertTo(desiredType))
            {
                return(converter.ConvertTo(evaluationResult !, desiredType));
            }

            var targetConverter = TypeDescriptor.GetConverter(desiredType);

            if (targetConverter.CanConvertFrom(evaluationResult !.GetType()))
            {
                return(targetConverter.ConvertFrom(evaluationResult !));
            }

            return(_wrapped.ConvertToDesiredType(evaluationResult, desiredType));
        }
예제 #22
0
        private object ConvertTo(Type destinationType, string value)
        {
            TypeConverter converter      = TypeDescriptor.GetConverter(destinationType);
            bool          canConvertFrom = converter.CanConvertFrom(value.GetType());

            if (!canConvertFrom)
            {
                converter = TypeDescriptor.GetConverter(value.GetType());
            }

            try
            {
                object convertedValue = (canConvertFrom)
                                            ? converter.ConvertFrom(null /* context */, CultureInfo.CurrentCulture, value)
                                            : converter.ConvertTo(null /* context */, CultureInfo.CurrentCulture, value, destinationType);
                return(convertedValue);
            }
            catch (Exception ex)
            {
                string message = String.Format("Could not convert header value from string to {0}", destinationType.FullName);
                throw new InvalidOperationException(message, ex);
            }
        }
예제 #23
0
        /// <summary>
        ///     Checks whether a string can be converted to the specified data type.
        /// </summary>
        /// <returns>
        ///     true if <paramref name="value" /> can be converted to the specified type; otherwise, false.
        /// </returns>
        /// <param name="value">The value to test.</param>
        /// <typeparam name="TValue">The data type to convert to.</typeparam>
        public static bool Is <TValue>(this string value)
        {
            var converter = TypeDescriptor.GetConverter(typeof(TValue));

            try
            {
                if (value != null)
                {
                    if (!converter.CanConvertFrom(typeof(string)))
                    {
                        return(false);
                    }
                }
                converter.ConvertFrom(value);
                return(true);
            }
            catch
            {
                // ignored
            }

            return(false);
        }
예제 #24
0
        public static T ToEntity <T>(this string obj) where T : class, new()
        {
            PropertyInfo[] piPropiedades = typeof(T).GetProperties();
            T       returnObj            = new();
            JObject jObj = JObject.Parse(obj);

            foreach (PropertyInfo piPropiedad in piPropiedades)
            {
                try
                {
                    string        stringValue = (string)jObj.SelectToken(piPropiedad.Name);
                    TypeConverter tc          = TypeDescriptor.GetConverter(piPropiedad.PropertyType);
                    if (stringValue != null)
                    {
                        object value = tc.ConvertFromString(null, CultureInfo.InvariantCulture, stringValue);
                        piPropiedad.SetValue(returnObj, value);
                    }
                }
                catch { }
            }

            return(returnObj);
        }
예제 #25
0
        public static bool TryConvertTo(this string value, Type targetType, out object result, TypeConverter converter = null, ITypeDescriptorContext context = null, CultureInfo culture = null)
        {
            if (converter == null)
            {
                converter = TypeDescriptor.GetConverter(targetType);
            }

            if (converter.CanConvertFrom(context, typeof(string)))
            {
                if (culture == null)
                {
                    culture = CultureInfo.InvariantCulture;
                }

                result = converter.ConvertFrom(context, culture, value);
                return(true);
            }
            else
            {
                result = targetType.GetDefaultValue();
                return(false);
            }
        }
예제 #26
0
 public static T Convert <T>(this String input)
 {
     try
     {
         var converter = TypeDescriptor.GetConverter(typeof(T));
         if (converter != null)
         {
             if (input == "")
             {
                 if (typeof(T) != typeof(String))
                 {
                     input = "0";
                 }
             }
             return((T)converter.ConvertFromString(input));
         }
         return(default(T));
     }
     catch (NotSupportedException)
     {
         return(default(T));
     }
 }
예제 #27
0
        /// <summary>
        /// Try to convert a value
        /// </summary>
        /// <param name="sourceValue">Value to convert</param>
        /// <param name="targetType">Type to convert to</param>
        /// <param name="convertedValue">Converted value</param>
        /// <returns>true if successful; otherwise false.</returns>
        public bool TryConvert(object sourceValue, Type targetType, out object convertedValue)
        {
            var tc = TypeDescriptor.GetConverter(targetType);

            if (!tc.CanConvertFrom(sourceValue.GetType()))
            {
                try
                {
                    convertedValue = Convert.ChangeType(sourceValue, targetType);
                    return(true);
                }
// ReSharper disable EmptyGeneralCatchClause
                catch
// ReSharper restore EmptyGeneralCatchClause
                {
                }
                convertedValue = null;
                return(false);
            }

            convertedValue = tc.ConvertFrom(sourceValue);
            return(true);
        }
예제 #28
0
파일: Utils.cs 프로젝트: ciker/enode
        /// <summary>Convert the given object to a given strong type.
        /// </summary>
        public static T ConvertType <T>(object value)
        {
            if (value == null)
            {
                return(default(T));
            }

            var typeConverter1 = TypeDescriptor.GetConverter(typeof(T));

            if (typeConverter1.CanConvertFrom(value.GetType()))
            {
                return((T)typeConverter1.ConvertFrom(value));
            }

            var typeConverter2 = TypeDescriptor.GetConverter(value.GetType());

            if (typeConverter2.CanConvertTo(typeof(T)))
            {
                return((T)typeConverter2.ConvertTo(value, typeof(T)));
            }

            return((T)Convert.ChangeType(value, typeof(T)));
        }
예제 #29
0
        private void TestWindowPlacement_TypeConverter()
        {
            var windowPlacement = WindowPlacement.Create();

            windowPlacement.MinPosition    = new NativePoint(10, 10);
            windowPlacement.MaxPosition    = new NativePoint(100, 100);
            windowPlacement.NormalPosition = new NativeRect(100, 100, 200, 200);
            windowPlacement.ShowCmd        = ShowWindowCommands.Normal;

            var typeConverter = TypeDescriptor.GetConverter(typeof(WindowPlacement));

            Assert.NotNull(typeConverter);
            var stringRepresentation = typeConverter.ConvertToInvariantString(windowPlacement);

            Assert.Equal("Normal|10,10|100,100|100,100,200,200", stringRepresentation);
            var windowPlacementResult = (WindowPlacement?)typeConverter.ConvertFromInvariantString(stringRepresentation);

            Assert.True(windowPlacementResult.HasValue);
            if (windowPlacementResult.HasValue)
            {
                Assert.Equal(windowPlacement, windowPlacementResult.Value);
            }
        }
예제 #30
0
        private static bool IsComplexType(this Type type)
        {
            switch (Type.GetTypeCode(type))
            {
            case TypeCode.Object:
                TypeConverter converter = TypeDescriptor.GetConverter(type);
                if (converter != null && !(converter is ComponentConverter) && converter.GetType() != typeof(TypeConverter))
                {
                    if (converter.CanConvertTo(typeof(string)) & converter.CanConvertFrom(typeof(string)))
                    {
                        return(false);
                    }
                }
                if (type.GetType() == typeof(Type))
                {
                    return(false);
                }
                return(true);

            default:
                return(false);
            }
        }