コード例 #1
0
        /// <summary>
        /// Converts an object o of type t to a string.
        /// </summary>
        /// <param name="o">The object to convert.</param>
        /// <returns>An object of the result type.</returns>
        /// <remarks>
        /// The object type should either be an IConvertible or have a TypeConverterAttribute,
        /// which points to a converter type capable of converting the object into a string
        /// and vice versa.
        /// </remarks>
        public static string ToString(object o)
        {
            IConvertible convertible = o as IConvertible;

            if (convertible != null)
            {
                return(convertible.ToString(CultureInfo.InvariantCulture));
            }

            Type t = o.GetType();

            object[] attrs = t.GetCustomAttributes(typeof(TypeConverterAttribute), true);
            if (attrs.Length == 0)
            {
                throw new Exception("Can't convert " + t.FullName + " to a string.");
            }
            for (int i = 0; i < attrs.Length; i++)
            {
                TypeConverterAttribute tca = (TypeConverterAttribute)attrs[i];
                Type          convType     = Type.GetType(tca.ConverterTypeName);
                TypeConverter tc           = Activator.CreateInstance(convType) as TypeConverter;
                if (!tc.CanConvertTo(typeof(string)))
                {
                    continue;
                }
                return((string)tc.ConvertTo(o, typeof(string)));
            }
            throw new Exception("Can't convert " + t.FullName + " to a string.");
        }
コード例 #2
0
ファイル: Program.cs プロジェクト: tajisoft/MissionPlanner
            private static void AddTypeConverter(Type type, Type type1)
            {
                Attribute[] newAttributes = new Attribute[1];
                newAttributes[0] = new TypeConverterAttribute(type1);

                TypeDescriptor.AddAttributes(type, newAttributes);
            }
コード例 #3
0
                PropertyDescriptor ConvertPropertyDescriptor(PropertyDescriptor descriptor)
                {
                    var descriptionAttribute = GetDescriptionAttribute(descriptor);

                    if (descriptor.Name == "DependencySets")
                    {
                        var typeConverterAttribute = new TypeConverterAttribute(typeof(DependencySetConverter));
                        var attributes             = new Attribute[] { descriptionAttribute, typeConverterAttribute };
                        return(new SimplePropertyDescriptor(descriptor, "Dependencies", attributes));
                    }

                    if (descriptor.Name == "Authors" || descriptor.Name == "Owners")
                    {
                        var typeConverterAttribute = new TypeConverterAttribute(typeof(CommaDelimitedSetConverter));
                        var attributes             = new Attribute[] { descriptionAttribute, typeConverterAttribute };
                        return(new SetPropertyDescriptor(descriptor, attributes));
                    }

                    if (descriptor.Name == "Tags")
                    {
                        var typeConverterAttribute = new TypeConverterAttribute(typeof(TagSetConverter));
                        var attributes             = new Attribute[] { descriptionAttribute, typeConverterAttribute };
                        return(new SetPropertyDescriptor(descriptor, attributes));
                    }

                    if (descriptor.Name == "Description" || descriptor.Name == "Summary" || descriptor.Name == "ReleaseNotes")
                    {
                        var editorAttribute = new EditorAttribute(DesignTypes.MultilineStringEditor, DesignTypes.UITypeEditor);
                        return(new SimplePropertyDescriptor(descriptor, new Attribute[] { descriptionAttribute, editorAttribute }));
                    }

                    return(new SimplePropertyDescriptor(descriptor, new Attribute[] { descriptionAttribute }));
                }
コード例 #4
0
        internal static CommandLineArgument Create(CommandLineParser parser, ParameterInfo parameter)
        {
            if (parser == null)
            {
                throw new ArgumentNullException("parser");
            }
            if (parameter == null)
            {
                throw new ArgumentNullException("parameter");
            }
            ArgumentNameAttribute argumentNameAttribute = (ArgumentNameAttribute)Attribute.GetCustomAttribute(parameter, typeof(ArgumentNameAttribute));
            string argumentName = argumentNameAttribute == null ? parameter.Name : argumentNameAttribute.ArgumentName;
            DescriptionAttribute descriptionAttribute = (DescriptionAttribute)Attribute.GetCustomAttribute(parameter, typeof(DescriptionAttribute));
            string description  = descriptionAttribute == null ? null : descriptionAttribute.Description;
            object defaultValue = ((parameter.Attributes & ParameterAttributes.HasDefault) == ParameterAttributes.HasDefault) ? parameter.DefaultValue : null;
            ValueDescriptionAttribute valueDescriptionAttribute = (ValueDescriptionAttribute)Attribute.GetCustomAttribute(parameter, typeof(ValueDescriptionAttribute));
            string valueDescription                       = valueDescriptionAttribute == null ? null : valueDescriptionAttribute.ValueDescription;
            bool   allowDuplicateDictionarykeys           = Attribute.IsDefined(parameter, typeof(AllowDuplicateDictionaryKeysAttribute));
            TypeConverterAttribute typeConverterAttribute = (TypeConverterAttribute)Attribute.GetCustomAttribute(parameter, typeof(TypeConverterAttribute));
            Type           converterType                  = typeConverterAttribute == null ? null : Type.GetType(typeConverterAttribute.ConverterTypeName, true);
            string         multiValueSeparator            = GetMultiValueSeparator((MultiValueSeparatorAttribute)Attribute.GetCustomAttribute(parameter, typeof(MultiValueSeparatorAttribute)));
            IList <string> aliases = GetAliases(Attribute.GetCustomAttributes(parameter, typeof(AliasAttribute)), argumentName);

            return(new CommandLineArgument(parser, null, parameter.Name, argumentName, aliases, parameter.ParameterType, converterType, parameter.Position, !parameter.IsOptional, defaultValue, description, valueDescription, multiValueSeparator, allowDuplicateDictionarykeys));
        }
コード例 #5
0
ファイル: Startup.cs プロジェクト: KollaRajesh/CodeSamples
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers(options =>
            {
                options.ModelBinderProviders.Insert(0, new DateBindingProvider());
            })
            //.AddNewtonsoftJson(options => options.SerializerSettings.Converters.Add(new DateNewtonsoftJsonConverter()));
            .AddJsonOptions(options => options.JsonSerializerOptions.Converters.Add(new DateJsonConverter()));

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "My API", Version = "v1"
                });
                c.MapType <Date>(() => new OpenApiSchema {
                    Type    = "string", Format = "date",
                    Example = new CustomOpenApiDateTime(new DateTime(2020, 1, 1))
                });

                // Set the comments path for the Swagger JSON and UI.
                string xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                string xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                c.IncludeXmlComments(xmlPath);
            });

            TypeConverterAttribute typeConverterAttribute = new TypeConverterAttribute(typeof(CustomParameterTypeConverter));

            TypeDescriptor.AddAttributes(typeof(Date), typeConverterAttribute);
        }
コード例 #6
0
        TypeConverter ICustomTypeDescriptor.GetConverter()
        {
            if (_converter == null)
            {
                TypeConverterAttribute attr =
                    _td.GetAttributes()[typeof(TypeConverterAttribute)] as TypeConverterAttribute;

                if (attr != null && !string.IsNullOrEmpty(attr.ConverterTypeName))
                {
                    Type type = GetTypeByName(attr.ConverterTypeName);

                    if (type != null && typeof(TypeConverter).IsAssignableFrom(type))
                    {
                        _converter = (TypeConverter)CreateInstance(type);
                    }
                }

                if (_converter == null)
                {
                    _converter = new TypeConverter();
                }
            }

            return(_converter);
        }
コード例 #7
0
        public APGenElementMap(Type type)
        {
            _properties = new APGenPropertyCollection();

            _collectionAttribute = Attribute.GetCustomAttribute(type, typeof(APGenCollectionAttribute)) as APGenCollectionAttribute;

            PropertyInfo[] props = type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance);

            foreach (PropertyInfo prop in props)
            {
                APGenPropertyAttribute attr = Attribute.GetCustomAttribute(prop, typeof(APGenPropertyAttribute)) as APGenPropertyAttribute;
                if (attr == null)
                {
                    continue;
                }
                string name = attr.Name != null ? attr.Name : prop.Name;

                APValidatorAttribute validatorAttr = Attribute.GetCustomAttribute(prop, typeof(APValidatorAttribute)) as APValidatorAttribute;
                APValidatorBase      validator     = validatorAttr != null ? validatorAttr.ValidatorInstance : null;

                TypeConverterAttribute convertAttr = Attribute.GetCustomAttribute(prop, typeof(TypeConverterAttribute)) as TypeConverterAttribute;
                TypeConverter          converter   = convertAttr != null ? (TypeConverter)Activator.CreateInstance(Type.GetType(convertAttr.ConverterTypeName), true) : null;

                APGenProperty property = new APGenProperty(name, prop.PropertyType, attr.DefaultValue, converter, validator, attr.Options);

                property.CollectionAttribute = Attribute.GetCustomAttribute(prop, typeof(APGenCollectionAttribute)) as APGenCollectionAttribute;
                _properties.Add(property);
            }
        }
コード例 #8
0
        public ElementMap(Type t)
        {
            properties = new ConfigurationPropertyCollection();

            collectionAttribute = Attribute.GetCustomAttribute(t, typeof(ConfigurationCollectionAttribute)) as ConfigurationCollectionAttribute;

            PropertyInfo[] props = t.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance);
            foreach (PropertyInfo prop in props)
            {
                ConfigurationPropertyAttribute at = Attribute.GetCustomAttribute(prop, typeof(ConfigurationPropertyAttribute)) as ConfigurationPropertyAttribute;
                if (at == null)
                {
                    continue;
                }
                string name = at.Name != null ? at.Name : prop.Name;

                ConfigurationValidatorAttribute validatorAttr = Attribute.GetCustomAttribute(prop, typeof(ConfigurationValidatorAttribute)) as ConfigurationValidatorAttribute;
                ConfigurationValidatorBase      validator     = validatorAttr != null ? validatorAttr.ValidatorInstance : null;

                TypeConverterAttribute convertAttr = (TypeConverterAttribute)Attribute.GetCustomAttribute(prop, typeof(TypeConverterAttribute));
                TypeConverter          converter   = convertAttr != null ? (TypeConverter)Activator.CreateInstance(Type.GetType(convertAttr.ConverterTypeName), true) : null;
                ConfigurationProperty  cp          = new ConfigurationProperty(name, prop.PropertyType, at.DefaultValue, converter, validator, at.Options);

                cp.CollectionAttribute = Attribute.GetCustomAttribute(prop, typeof(ConfigurationCollectionAttribute)) as ConfigurationCollectionAttribute;
                properties.Add(cp);
            }
        }
コード例 #9
0
        internal static CommandLineArgument Create(CommandLineParser parser, PropertyInfo property)
        {
            if (parser == null)
            {
                throw new ArgumentNullException("parser");
            }
            if (property == null)
            {
                throw new ArgumentNullException("property");
            }
            CommandLineArgumentAttribute attribute = (CommandLineArgumentAttribute)Attribute.GetCustomAttribute(property, typeof(CommandLineArgumentAttribute));

            if (attribute == null)
            {
                throw new ArgumentException(Properties.Resources.MissingArgumentAttribute, "property");
            }
            string argumentName = attribute.ArgumentName ?? property.Name;
            object defaultValue = attribute.DefaultValue;
            DescriptionAttribute descriptionAttribute = (DescriptionAttribute)Attribute.GetCustomAttribute(property, typeof(DescriptionAttribute));
            string description                            = descriptionAttribute == null ? null : descriptionAttribute.Description;
            string valueDescription                       = attribute.ValueDescription; // If null, the ctor will sort it out.
            int?   position                               = attribute.Position < 0 ? null : (int?)attribute.Position;
            bool   allowDuplicateDictionarykeys           = Attribute.IsDefined(property, typeof(AllowDuplicateDictionaryKeysAttribute));
            TypeConverterAttribute typeConverterAttribute = (TypeConverterAttribute)Attribute.GetCustomAttribute(property, typeof(TypeConverterAttribute));
            Type           converterType                  = typeConverterAttribute == null ? null : Type.GetType(typeConverterAttribute.ConverterTypeName, true);
            string         multiValueSeparator            = GetMultiValueSeparator((MultiValueSeparatorAttribute)Attribute.GetCustomAttribute(property, typeof(MultiValueSeparatorAttribute)));
            IList <string> aliases                        = GetAliases(Attribute.GetCustomAttributes(property, typeof(AliasAttribute)), argumentName);

            return(new CommandLineArgument(parser, property, property.Name, argumentName, aliases, property.PropertyType, converterType, position, attribute.IsRequired, defaultValue, description, valueDescription, multiValueSeparator, allowDuplicateDictionarykeys));
        }
コード例 #10
0
        /// <summary>
        /// Converts the string o to an object of type t.
        /// </summary>
        /// <param name="o">The string to convert.</param>
        /// <param name="t">The result type.</param>
        /// <returns>An object of the result type.</returns>
        /// <remarks>
        /// The type t should either be an IConvertible or have a TypeConverterAttribute,
        /// which points to a converter type capable of converting objects of type t into a string
        /// and vice versa.
        /// </remarks>
        public static object FromString(object o, Type t)
        {
            string valueString = (string)o;

            // First try, if we can use IConvertible
            if (typeof(IConvertible).IsAssignableFrom(t))
            {
                return(((IConvertible)valueString).ToType(t, CultureInfo.InvariantCulture));
            }

            // Now try TypeConverters
            object[] attrs = t.GetCustomAttributes(typeof(TypeConverterAttribute), true);
            if (attrs.Length == 0)
            {
                goto throwEx;
            }

            for (int i = 0; i < attrs.Length; i++)
            {
                TypeConverterAttribute tca = (TypeConverterAttribute)attrs[i];
                Type          convType     = Type.GetType(tca.ConverterTypeName);
                TypeConverter tc           = Activator.CreateInstance(convType) as TypeConverter;
                if (!tc.CanConvertFrom(typeof(string)))
                {
                    continue;
                }
                return(tc.ConvertFrom(valueString));
            }

throwEx:
            throw new NDOException(107, "Can't convert " + valueString.GetType().FullName + " to " + t.FullName + ". The source type has to be an IConvertible or has to provide a TypeConverter using a TypeConverterAttribute.");
        }
コード例 #11
0
        /// <summary>
        /// Gets the bound property converter.
        /// </summary>
        /// <returns></returns>
        private TypeConverter GetBoundPropertyConverter()
        {
            PropertyDescriptor property = GetBoundProperty();
            TypeConverter      converterInstance;
            string             converterName = TypeConverter;

            if (String.IsNullOrEmpty(converterName) && property != null)
            {
                TypeConverterAttribute converterAttr = (TypeConverterAttribute)property.Attributes[typeof(TypeConverterAttribute)];
                if (converterAttr != null && !String.IsNullOrEmpty(converterAttr.ConverterTypeName))
                {
                    converterName = converterAttr.ConverterTypeName;
                }
            }

            if (!String.IsNullOrEmpty(converterName))
            {
                Type converterType = LoadType(converterName);
                converterInstance = (TypeConverter)Activator.CreateInstance(converterType);
            }
            else
            {
                converterInstance = TypeDescriptor.GetConverter(ValueType);
            }

            return(converterInstance);
        }
コード例 #12
0
        private Tup CanHandle2(Control control, Type dataType)
        {
            TypeConverterAttribute attr = dataType.GetCustomAttribute <TypeConverterAttribute>();

            if (attr == null)
            {
                return(null);
            }

            Type converterType = Type.GetType(attr.ConverterTypeName);

            if (converterType == null)
            {
                return(null);
            }

            TypeConverter converter = (TypeConverter)Activator.CreateInstance(converterType);

            foreach (Binder binder in _collection)
            {
                if (binder.PreferredDataType != null &&
                    (control == null || binder.CanHandle(control, binder.PreferredDataType)) &&
                    converter.CanConvertFrom(binder.PreferredDataType) &&
                    converter.CanConvertTo(binder.PreferredDataType))
                {
                    return(new Tup(converter, binder));
                }
            }

            return(null);
        }
コード例 #13
0
        protected void SetPropertyValue(Control control, string propertyName, string propertyValue)
        {
            object obj2 = null;
            InstanceAndPropertyInfo memberInfo   = GetMemberInfo(control, propertyName);
            PropertyInfo            propertyInfo = memberInfo.PropertyInfo;
            TypeConverter           converter    = null;
            TypeConverterAttribute  attribute    = Attribute.GetCustomAttribute(propertyInfo, typeof(TypeConverterAttribute), true) as TypeConverterAttribute;

            if (attribute != null)
            {
                Type type = Type.GetType(attribute.ConverterTypeName, false);
                if (type != null)
                {
                    converter = (TypeConverter)Activator.CreateInstance(type);
                }
            }
            if ((converter != null) && converter.CanConvertFrom(typeof(string)))
            {
                obj2 = converter.ConvertFromInvariantString(propertyValue);
            }
            else
            {
                converter = TypeDescriptor.GetConverter(propertyInfo.PropertyType);
                if ((converter != null) && converter.CanConvertFrom(typeof(string)))
                {
                    obj2 = converter.ConvertFromInvariantString(propertyValue);
                }
            }
            propertyInfo.SetValue(memberInfo.Instance, obj2, null);
        }
コード例 #14
0
        private TypeConverter GetTypeConverter()
        {
            Type t = typeof(HtmlTableCell);

            PropertyInfo[] props;
            PropertyInfo   pi = null;
            TypeConverter  tc;

            props = t.GetProperties();

            foreach (PropertyInfo p in props)
            {
                if (p.Name == "NoWrap")
                {
                    pi = p;
                    break;
                }
            }

            object[] attrs             = pi.GetCustomAttributes(typeof(TypeConverterAttribute), false);
            TypeConverterAttribute tca = (TypeConverterAttribute)attrs[0];

            Type tct = Type.GetType(tca.ConverterTypeName);

            tc = (TypeConverter)Activator.CreateInstance(tct);

            return(tc);
        }
コード例 #15
0
        private void SetXmlValue(object obj, string attrName, string attrValue)
        {
            PropertyInfo property = obj.GetType().GetProperty(attrName);

            if (property != null)
            {
                object value = attrValue;
                if (property.PropertyType == typeof(string))
                {
                    value = attrValue;
                }
                else if (property.PropertyType == typeof(Font))
                {
                    value = (Font)SerializerBase.fontConverter.ConvertFromString(null, CultureInfo.InvariantCulture, attrValue);
                }
                else if (property.PropertyType == typeof(Color))
                {
                    value = (Color)SerializerBase.colorConverter.ConvertFromString(null, CultureInfo.InvariantCulture, attrValue);
                }
                else if (property.PropertyType == typeof(Image))
                {
                    value = SerializerBase.ImageFromString(attrValue);
                }
                else
                {
                    PropertyDescriptor propertyDescriptor = TypeDescriptor.GetProperties(obj)[attrName];
                    bool flag = false;
                    if (propertyDescriptor != null)
                    {
                        try
                        {
                            TypeConverterAttribute typeConverterAttribute = (TypeConverterAttribute)propertyDescriptor.Attributes[typeof(TypeConverterAttribute)];
                            if (typeConverterAttribute != null && typeConverterAttribute.ConverterTypeName.Length > 0)
                            {
                                Assembly      assembly      = Assembly.GetAssembly(GetType());
                                string[]      array         = typeConverterAttribute.ConverterTypeName.Split(',');
                                TypeConverter typeConverter = (TypeConverter)assembly.CreateInstance(array[0]);
                                if (typeConverter != null && typeConverter.CanConvertFrom(typeof(string)))
                                {
                                    value = typeConverter.ConvertFromString(null, CultureInfo.InvariantCulture, attrValue);
                                    flag  = true;
                                }
                            }
                        }
                        catch (Exception)
                        {
                        }
                        if (!flag && propertyDescriptor.Converter != null && propertyDescriptor.Converter.CanConvertFrom(typeof(string)))
                        {
                            value = propertyDescriptor.Converter.ConvertFromString(null, CultureInfo.InvariantCulture, attrValue);
                        }
                    }
                }
                property.SetValue(obj, value, null);
            }
            else if (!base.IgnoreUnknownAttributes)
            {
                throw new InvalidOperationException(Utils.SRGetStr("ExceptionSerializerUnknownProperty", attrName, obj.GetType().ToString()));
            }
        }
コード例 #16
0
        private static void SetTypeConverter(ParameterInfo parameterInfo, bool allowMultipleValues, ref TypeConverter typeConverter, ref Flags flags)
        {
            TypeConverterAttribute typeConverterAttribute = parameterInfo.GetCustomAttribute <TypeConverterAttribute>();

            if (typeConverterAttribute != null && !string.IsNullOrEmpty(typeConverterAttribute.ConverterTypeName))
            {
                Type typeConverterType = Type.GetType(typeConverterAttribute.ConverterTypeName);

                if (typeConverterType != null && typeof(TypeConverter).IsAssignableFrom(typeConverterType))
                {
                    typeConverter = (TypeConverter)Activator.CreateInstance(typeConverterType);
                }
            }

            if (typeConverter == null)
            {
                Type parameterType = parameterInfo.ParameterType;

                if (parameterType.IsEnum)
                {
                    if (parameterType.IsDefined(typeof(FlagsAttribute), false))
                    {
                        typeConverter = new FlagEnumConverter(parameterType);
                        flags        |= Flags.IsBitField;
                    }
                    else
                    {
                        typeConverter = new EnumConverter(parameterType);
                        flags        |= Flags.IsEnum;
                    }
                }
                else
                {
                    if (allowMultipleValues)
                    {
                        typeConverter = new CollectionConverter(parameterType);
                    }
                    else
                    {
                        typeConverter = TypeDescriptor.GetConverter(parameterType);
                    }
                }
            }

            if (allowMultipleValues)
            {
                if (!typeConverter.CanConvertFrom(typeof(IEnumerable <string>)))
                {
                    throw new InvalidOperationException();
                }
            }
            else
            {
                if (!typeConverter.CanConvertFrom(typeof(string)))
                {
                    throw new InvalidOperationException();
                }
            }
        }
コード例 #17
0
        private void UpdateProperties()
        {
            if (mInstance != null)
            {
                // This only removes
                // native members that
                // haven't been explicitly
                // added.  Explicitly-added
                // members may have TypeConverters
                // so we want to preserve those.
                ClearNonExplicitNativeMembers();

                PropertyInfo[] propertyInfos = mInstance.GetType().GetProperties(

                    BindingFlags.Instance | BindingFlags.Public | BindingFlags.GetProperty // I don't think we want to show static members in PropertyGrids
                    );

                foreach (PropertyInfo propertyInfo in propertyInfos)
                {
                    if (!mExcludedMembers.Contains(propertyInfo.Name) && !mCustomPropertyGridMembers.ContainsMember(propertyInfo.Name))
                    {
                        PropertyGridMember pgm = new PropertyGridMember();
                        pgm.Name = propertyInfo.Name;
                        pgm.Type = propertyInfo.PropertyType;

                        pgm.SetAttributes(propertyInfo.GetCustomAttributes(true));
                        pgm.IsReadOnly = propertyInfo.CanWrite == false;
                        // Does this thing have a type converter set on the property?
                        TypeConverterAttribute attrib =
                            (TypeConverterAttribute)Attribute.GetCustomAttribute(propertyInfo,
                                                                                 typeof(TypeConverterAttribute));
                        if (attrib != null)
                        {
                            TypeConverter converter =
                                (TypeConverter)Activator.CreateInstance(Type.GetType(attrib.ConverterTypeName),
                                                                        false);
                            pgm.TypeConverter = converter;
                        }

                        mNativePropertyGridMembers.Add(pgm);
                    }
                }

                FieldInfo[] fieldInfos = mInstance.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.GetField);
                foreach (FieldInfo fieldInfo in fieldInfos)
                {
                    if (!mExcludedMembers.Contains(fieldInfo.Name) && !mCustomPropertyGridMembers.ContainsMember(fieldInfo.Name))
                    {
                        PropertyGridMember pgm = new PropertyGridMember()
                        {
                            Name = fieldInfo.Name,
                            Type = fieldInfo.FieldType
                        };

                        mNativePropertyGridMembers.Add(pgm);
                    }
                }
            }
        }
コード例 #18
0
        public static TypeConverter GetConverter(Type itemType)
        {
            TypeConverter converter = TypeDescriptor.GetConverter(itemType);

            if (converter == null || converter.GetType() == typeof(TypeConverter))
            {
                // We got an invalid converter.  WPF will do this if the converter
                // is internal, but we use internal converters all over the place
                // at design time.  Detect this and build the converter ourselves.

                if (converterCache != null)
                {
                    converter = (TypeConverter)converterCache[itemType];
                    if (converter != null)
                    {
                        return(converter);
                    }
                }

                AttributeCollection    attrs = TypeDescriptor.GetAttributes(itemType);
                TypeConverterAttribute tca   = attrs[typeof(TypeConverterAttribute)] as TypeConverterAttribute;
                if (tca != null && tca.ConverterTypeName != null)
                {
                    Type type = Type.GetType(tca.ConverterTypeName);
                    if (type != null && !type.IsPublic && typeof(TypeConverter).IsAssignableFrom(type))
                    {
                        ConstructorInfo ctor = type.GetConstructor(new Type[] { typeof(Type) });
                        if (ctor != null)
                        {
                            converter = (TypeConverter)ctor.Invoke(new object[] { itemType });
                        }
                        else
                        {
                            converter = (TypeConverter)Activator.CreateInstance(type);
                        }

                        lock (converterCacheSyncObject)
                        {
                            if (converterCache == null)
                            {
                                converterCache = new Hashtable();

                                // Listen to type changes and clear the cache.
                                // This allows new metadata tables to be installed

                                TypeDescriptor.Refreshed += delegate(RefreshEventArgs args)
                                {
                                    converterCache.Remove(args.TypeChanged);
                                };
                            }

                            converterCache[itemType] = converter;
                        }
                    }
                }
            }

            return(converter);
        }
コード例 #19
0
 public CommandArgument(
     Type parameterType, ParameterKind parameterKind, PropertyInfo property, string description,
     TypeConverterAttribute converter, CommandArgumentAttribute argument, IEnumerable <ParameterValidationAttribute> validators)
     : base(parameterType, parameterKind, property, description, converter, validators, argument.IsRequired)
 {
     Value    = argument.ValueName;
     Position = argument.Position;
 }
コード例 #20
0
 public static void AddTo(Type type)
 {
     if (type != null)
     {
         TypeConverterAttribute tt = new TypeConverterAttribute(typeof(PropertyGridTypeConverter));
         TypeDescriptor.AddAttributes(type, new Attribute[] { tt });
     }
 }
コード例 #21
0
        public static void RegisterExpression <T>()
        {
            var attribute = new Attribute[1];
            var vConv     = new TypeConverterAttribute(typeof(BindingExpressionConverter));

            attribute[0] = vConv;
            TypeDescriptor.AddAttributes(typeof(T), attribute);
        }
コード例 #22
0
ファイル: GuiHelper_Controls.cs プロジェクト: olesar/Altaxo
        /// <summary>
        /// Registers a converter for a provided type.
        /// </summary>
        /// <typeparam name="T">The type for which the converter is to be registered.</typeparam>
        /// <typeparam name="TC">The type of the converter.</typeparam>
        public static void RegisterConverter <T, TC>()
        {
            var attr  = new Attribute[1];
            var vConv = new TypeConverterAttribute(typeof(TC));

            attr[0] = vConv;
            TypeDescriptor.AddAttributes(typeof(T), attr);
        }
コード例 #23
0
 public CommandArgument(
     Type parameterType, ParameterKind parameterKind, PropertyInfo property, string description,
     TypeConverterAttribute converter, CommandArgumentAttribute argument)
     : base(parameterType, parameterKind, property, description, converter, argument.IsRequired)
 {
     Value    = argument.Value;
     Position = argument.Position;
 }
コード例 #24
0
    /// <summary>
    /// Registers which converter is responsible for which type.
    /// </summary>
    /// <typeparam name="T">The type.</typeparam>
    /// <typeparam name="TC">The converter.</typeparam>
    public static void Register <T, TC>()
    {
        Attribute[]            attribute = new Attribute[1];
        TypeConverterAttribute typeConverterAttribute = new TypeConverterAttribute(typeof(TC));

        attribute[0] = typeConverterAttribute;
        TypeDescriptor.AddAttributes(typeof(T), attribute);
    }
コード例 #25
0
        public static void Register <T, TC>() where TC : TypeConverter
        {
            Attribute[]            attr  = new Attribute[1];
            TypeConverterAttribute vConv = new TypeConverterAttribute(typeof(TC));

            attr[0] = vConv;
            TypeDescriptor.AddAttributes(typeof(T), attr);
        }
コード例 #26
0
        protected override void PreFilterProperties(IDictionary properties)
        {
            int num2;

            base.PreFilterProperties(properties);
            PropertyDescriptor oldPropertyDescriptor = (PropertyDescriptor)properties["DataSource"];

            System.ComponentModel.AttributeCollection attributes = oldPropertyDescriptor.Attributes;
            int    index      = -1;
            int    count      = attributes.Count;
            string dataSource = this.DataSource;

            if (dataSource.Length > 0)
            {
                this._keepDataSourceBrowsable = true;
            }
            for (int i = 0; i < attributes.Count; i++)
            {
                if (attributes[i] is BrowsableAttribute)
                {
                    index = i;
                    break;
                }
            }
            if (((index == -1) && (dataSource.Length == 0)) && !this._keepDataSourceBrowsable)
            {
                num2 = count + 2;
            }
            else
            {
                num2 = count + 1;
            }
            Attribute[] array = new Attribute[num2];
            attributes.CopyTo(array, 0);
            array[count] = new TypeConverterAttribute(typeof(DataSourceConverter));
            if ((dataSource.Length == 0) && !this._keepDataSourceBrowsable)
            {
                if (index == -1)
                {
                    array[count + 1] = BrowsableAttribute.No;
                }
                else
                {
                    array[index] = BrowsableAttribute.No;
                }
            }
            oldPropertyDescriptor      = TypeDescriptor.CreateProperty(base.GetType(), "DataSource", typeof(string), array);
            properties["DataSource"]   = oldPropertyDescriptor;
            oldPropertyDescriptor      = (PropertyDescriptor)properties["DataMember"];
            oldPropertyDescriptor      = TypeDescriptor.CreateProperty(base.GetType(), oldPropertyDescriptor, new Attribute[] { new TypeConverterAttribute(typeof(DataMemberConverter)) });
            properties["DataMember"]   = oldPropertyDescriptor;
            oldPropertyDescriptor      = (PropertyDescriptor)properties["DataKeyField"];
            oldPropertyDescriptor      = TypeDescriptor.CreateProperty(base.GetType(), oldPropertyDescriptor, new Attribute[] { new TypeConverterAttribute(typeof(DataFieldConverter)) });
            properties["DataKeyField"] = oldPropertyDescriptor;
            oldPropertyDescriptor      = (PropertyDescriptor)properties["DataSourceID"];
            oldPropertyDescriptor      = TypeDescriptor.CreateProperty(base.GetType(), oldPropertyDescriptor, new Attribute[] { new TypeConverterAttribute(typeof(DataSourceIDConverter)) });
            properties["DataSourceID"] = oldPropertyDescriptor;
        }
コード例 #27
0
ファイル: DiffProvider.cs プロジェクト: replaysMike/AnyDiff
 private static TypeConverter GetTypeConverter(TypeConverterAttribute attribute)
 {
     if (attribute != null)
     {
         var typeConverter = Activator.CreateInstance(Type.GetType(attribute.ConverterTypeName)) as TypeConverter;
         return(typeConverter);
     }
     return(null);
 }
コード例 #28
0
        /// <summary>
        /// Sets the properties of the current action using the values provided, if possible.
        /// </summary>
        /// <param name="attributes">A <see cref="StringDictionary"/> containing the set of attributes
        /// to use to set the properties of the action.</param>
        public virtual void Configure(StringDictionary attributes)
        {
            PropertyDescriptorCollection props;
            ISite mysite = this.Site;

            try
            {
                // Must remove the site temporarily because
                // otherwise the TypeDescriptor doesn't work properly.
                this.Site = null;
                props     = TypeDescriptor.GetProperties(this);
            }
            finally
            {
                this.Site = mysite;
            }

            foreach (string key in attributes.Keys)
            {
                PropertyDescriptor prop = props[key];
                if (prop == null || prop.IsReadOnly)
                {
                    continue;
                }
                TypeConverter          converter = null;
                TypeConverterAttribute convattr  = (TypeConverterAttribute)prop.Attributes[typeof(TypeConverterAttribute)];
                if (convattr != null && !string.IsNullOrEmpty(convattr.ConverterTypeName))
                {
                    ITypeResolutionService resolutionService = (ITypeResolutionService)
                                                               ServiceHelper.GetService(this, typeof(ITypeResolutionService));
                    Type type = resolutionService.GetType(convattr.ConverterTypeName, true);
                    converter = (TypeConverter)Activator.CreateInstance(type);
                }
                else
                {
                    converter = TypeDescriptor.GetConverter(prop.PropertyType);
                }
                object value;
                try
                {
                    // Perform minimum conversion if necessary.
                    if (!prop.PropertyType.IsAssignableFrom(typeof(string)))
                    {
                        value = converter.ConvertFromString(new CustomDescriptor(this, prop), attributes[key]);
                    }
                    else
                    {
                        value = attributes[key];
                    }
                    prop.SetValue(this, value);
                }
                catch (TargetInvocationException e)
                {
                    throw e.InnerException;
                }
            }
        }
コード例 #29
0
        /// <summary>
        /// Overrides the original TypeConverter with the specified TypeConverter
        /// <remarks>Usefull for registering TypeConverters to Types that are closed such as library types</remarks>
        /// </summary>
        /// <typeparam name="T">The type to attach the specified converter to</typeparam>
        /// <typeparam name="TC">The converter that will handle all type conversions to and from the type</typeparam>
        public static void RegisterTypeConverter <T, TC>() where TC : System.ComponentModel.TypeConverter
        {
            TypeConverterAttribute tca = new TypeConverterAttribute(typeof(TC));

            if (!TypeDescriptor.GetAttributes(typeof(T)).Contains(tca))
            {
                TypeDescriptor.AddAttributes(typeof(T), tca);
            }
        }
コード例 #30
0
            public CustomPatternPropertyDescriptor(string displayName, object value, bool common)
                : base(displayName, null)
            {
                var categoryAttr      = new CategoryAttribute(common ? constPatternsCategory : constCustomPatternsCategory);
                var typeConverterAttr = new TypeConverterAttribute(typeof(ExpandableObjectConverter));

                _attributes = new AttributeCollection(categoryAttr, typeConverterAttr);
                _value      = value;
            }
コード例 #31
0
 private static ITypeConverter CreateConverterInstance(TypeConverterAttribute attribute)
 {
     return (ITypeConverter)Activator.CreateInstance(attribute.Converter, null);
 }