/// <summary> /// /// </summary> public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { if (value is string stringValue) { stringValue = stringValue.Trim(); if (stringValue == "Uniform" || stringValue == "Paced") { throw new NotSupportedException( $"The '{typeof(KeyTime)}.{stringValue}' property is not supported yet." ); } else if (stringValue.Length > 0 && stringValue[stringValue.Length - 1] == '%') { throw new NotSupportedException( $"Percentage values for '{typeof(KeyTime)}' are not supported yet." ); } else { TimeSpan timeSpanValue = (TimeSpan)TypeConverterHelper.GetConverter( typeof(TimeSpan)).ConvertFrom( context, culture, stringValue); return(KeyTime.FromTimeSpan(timeSpanValue)); } } throw GetConvertFromException(value); }
public static object GetPropertyValue(Type xamlType, string propertyName, string xamlValue, Func <object> fallbackValueFunc) { ReflectedPropertyData property = TypeConverterHelper.GetProperties(xamlType)[propertyName]; if (property == null) { throw new InvalidOperationException( $"Property '{propertyName}' was not found in type '{xamlType}'." ); } // Note: here we do not want to use the Converter property as it would return a non-null // converter for several known types for which object instantiation can be optimized at // compilation and we would waste time parsing strings. TypeConverter converter = property.InternalConverter; if (converter != null) { return(converter.ConvertFromInvariantString(xamlValue)); } if (fallbackValueFunc != null) { return(fallbackValueFunc()); } throw new InvalidOperationException( $"Failed to create a '{property.PropertyType}' from the text '{xamlValue}'." ); }
public void GetProperties_InternalConverter_When_Property_Is_Overridden_And_Base_Has_TypeConverterAttribute() { TypeConverterHelper.GetProperties(typeof(_MyClass2))[nameof(_MyClass2.ByteProperty)] .InternalConverter .Should() .BeNull(); }
private static object TryAddition(object currentValue, object value) { object returnValue = null; Type valueType = value.GetType(); Type additiveType = currentValue.GetType(); MethodInfo uniqueAdditionOperation = null; object convertedValue = value; foreach (MethodInfo additionOperation in additiveType.GetMethods()) { if (string.Compare(additionOperation.Name, "op_Addition", StringComparison.Ordinal) != 0) { continue; } ParameterInfo[] parameters = additionOperation.GetParameters(); Debug.Assert(parameters.Length == 2, "op_Addition is expected to have 2 parameters"); Type secondParameterType = parameters[1].ParameterType; if (!parameters[0].ParameterType.IsAssignableFrom(additiveType)) { continue; } else if (!secondParameterType.IsAssignableFrom(valueType)) { TypeConverter additionConverter = TypeConverterHelper.GetTypeConverter(secondParameterType); if (additionConverter.CanConvertFrom(valueType)) { convertedValue = TypeConverterHelper.DoConversionFrom(additionConverter, value); } else { continue; } } if (uniqueAdditionOperation != null) { throw new ArgumentException(string.Format( CultureInfo.CurrentCulture, ExceptionStringTable.ChangePropertyActionAmbiguousAdditionOperationExceptionMessage, additiveType.Name)); } uniqueAdditionOperation = additionOperation; } if (uniqueAdditionOperation != null) { returnValue = uniqueAdditionOperation.Invoke(null, new object[] { currentValue, convertedValue }); } else { // we couldn't figure out how to add, so pack it up and just set value returnValue = value; } return(returnValue); }
public void GetProperties_InternalConverter_When_No_TypeConverterAttribute() { TypeConverterHelper.GetProperties(typeof(_MyType1))[nameof(_MyType1.IntProperty)] .InternalConverter .Should() .BeNull(); }
public void GetConverter_When_Nullable_Of_CoreType() { var converter = TypeConverterHelper.GetConverter(typeof(Point?)); converter.Should() .NotBeNull() .And .BeOfType <NullableConverter2>(); converter.As <NullableConverter2>() .NullableType .Should() .BeSameAs(typeof(Point?)); converter.As <NullableConverter2>() .UnderlyingType .Should() .BeSameAs(typeof(Point)); converter.As <NullableConverter2>() .UnderlyingTypeConverter .Should() .NotBeNull() .And .BeOfType <PointConverter>(); }
public void GetProperties_InternalConverter_When_TypeConverterAttribute() { TypeConverterHelper.GetProperties(typeof(_MyType3))[nameof(_MyType3.DateTimeProperty)] .InternalConverter .Should() .BeOfType <_MyDateTimeConverter>(); }
/// <inheritdoc /> public async Task <object> GetAsync(int index, Type type) { if (type == null) { throw new ArgumentNullException(nameof(type)); } if (Length <= index) { throw new CommandIndexOutOfRangeException(m_OpenModStringLocalizer["commands:errors:out_of_range_error", new { Index = index, Type = type, Length }], index, Length); } if (index < 0) { throw new IndexOutOfRangeException(); } string arg = ToArray()[index]; //todo make type converters //if (typeof(IUser).IsAssignableFrom(type)) //{ // /* // * The logic for getting IUser and IUserInfo is as follows: // * If the name is supplied as usermanager:username, e.g. discord:Trojaner, it will search for valid "discord" user manager and return the "Trojaner" named user of it. // * Otherwise (if the user manager does not exist or the format was not supplied), it will use the player manager and return the user for the given input. // */ // IUserManager targetUserManager = container.Resolve<IPlayerManager>(); // string userName = arg; // if (arg.Contains(":")) // { // var args = arg.Split(':'); // string userManagerMapping = args.First(); // foreach (var userMgr in container.ResolveAll<IUserManager>()) // { // if (userMgr.ServiceName.Equals(userManagerMapping, StringComparison.OrdinalIgnoreCase)) // { // userName = string.Join(":", args.Skip(1).ToArray()); // targetUserManager = userMgr; // break; // } // } // } // return await targetUserManager.GetUserAsync(userName); //} TypeConverter converter = TypeConverterHelper.GetConverter(type); if (converter.CanConvertFrom(typeof(string))) { return(converter.ConvertFromWithServiceContext(m_ServiceProvider, arg)); } throw new CommandParameterParseException(m_OpenModStringLocalizer["commands:errors:parse_error", new { Value = arg, Type = type }], arg, type); }
public void GetProperties_Converter_When_TypeConverterAttribute_And_PropertyType_Has_TypeConverter() { TypeConverterHelper.GetProperties(typeof(_MyClass3))[nameof(_MyClass3.ByteProperty)] .Converter .Should() .BeOfType <_MyByteConverter1>(); }
public void GetProperties_Converter_When_No_TypeConverterAttribute_And_PropertyType_Has_No_TypeConverter() { TypeConverterHelper.GetProperties(typeof(_MyClass5))[nameof(_MyClass5.MyType1Property)] .Converter .Should() .BeNull(); }
public void GetProperties_Converter_When_No_TypeConverterAttribute_And_PropertyType_Has_TypeConverter() { TypeConverterHelper.GetProperties(typeof(_MyType1))[nameof(_MyType1.IntProperty)] .Converter .Should() .BeSameAs(TypeConverterHelper.GetConverter(typeof(int))); }
/// <inheritdoc /> public override bool Accept(Type targetRootType, Type targetMemberType, Type pastedDataType) { var sourceTypeDescriptor = TypeDescriptorFactory.Default.Find(pastedDataType); var targetTypeDescriptor = TypeDescriptorFactory.Default.Find(targetMemberType); // Can only paste a collection into another collection, or a dictionary into a dictionary if (sourceTypeDescriptor.Category == DescriptorCategory.Collection && targetTypeDescriptor.Category != DescriptorCategory.Collection || sourceTypeDescriptor.Category == DescriptorCategory.Dictionary && targetTypeDescriptor.Category != DescriptorCategory.Dictionary) { return(false); } // Special case: KeyValuePair<,> if (targetTypeDescriptor.Category == DescriptorCategory.Dictionary && sourceTypeDescriptor.Category != DescriptorCategory.Dictionary) { // Key and Value types must be compatible var sourceKeyType = sourceTypeDescriptor.Type.GetMember("Key").OfType <PropertyInfo>().FirstOrDefault()?.PropertyType; var sourceValueType = sourceTypeDescriptor.Type.GetMember("Value").OfType <PropertyInfo>().FirstOrDefault()?.PropertyType; return(sourceKeyType != null && TypeConverterHelper.CanConvert(sourceKeyType, ((DictionaryDescriptor)targetTypeDescriptor).KeyType) && sourceValueType != null && TypeConverterHelper.CanConvert(sourceValueType, ((DictionaryDescriptor)targetTypeDescriptor).ValueType)); } // Types must be compatible var sourceType = TypeDescriptorFactory.Default.Find(pastedDataType).GetInnerCollectionType(); var destinationType = TypeDescriptorFactory.Default.Find(targetMemberType).GetInnerCollectionType(); return(TypeConverterHelper.CanConvert(sourceType, destinationType)); }
private static bool ConvertForDictionary(DictionaryDescriptor dictionaryDescriptor, ref object data) { object convertedDictionary; if (DictionaryDescriptor.IsDictionary(data.GetType())) { if (!TryConvertDictionaryData(data, dictionaryDescriptor, out convertedDictionary)) { return(false); } } else { var dataType = data.GetType(); var key = dataType.GetMember("Key").OfType <PropertyInfo>().FirstOrDefault()?.GetValue(data); if (key == null || !TypeConverterHelper.TryConvert(key, dictionaryDescriptor.KeyType, out key)) { return(false); } var value = dataType.GetMember("Value").OfType <PropertyInfo>().FirstOrDefault()?.GetValue(data); if (value == null || !TypeConverterHelper.TryConvert(value, dictionaryDescriptor.ValueType, out value)) { return(false); } convertedDictionary = Activator.CreateInstance(dictionaryDescriptor.Type, true); dictionaryDescriptor.SetValue(convertedDictionary, key, value); } data = convertedDictionary; return(true); }
public void GetConverter_When_Nullable_Of_TypeConverterAttribute() { var converter = TypeConverterHelper.GetConverter(typeof(MyStruct1?)); converter.Should() .NotBeNull() .And .BeOfType <NullableConverter2>(); converter.As <NullableConverter2>() .NullableType .Should() .BeSameAs(typeof(MyStruct1?)); converter.As <NullableConverter2>() .UnderlyingType .Should() .BeSameAs(typeof(MyStruct1)); converter.As <NullableConverter2>() .UnderlyingTypeConverter .Should() .NotBeNull() .And .BeOfType <MyStruct1Converter>(); }
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { if (value is string stringValue) { TypeConverterHelper currentHelper = helper; if (currentHelper == null) { IDestinationTypeProvider targetService = context.GetService(typeof(IDestinationTypeProvider)) as IDestinationTypeProvider; Type targetType = targetService.GetDestinationType(); if (!this.helpers.Value.TryGetValue(targetType, out currentHelper)) { currentHelper = GetTypeConverterHelper(targetType, this.baseType, this.helperType); if (!this.helpers.Value.TryAdd(targetType, currentHelper)) { if (!this.helpers.Value.TryGetValue(targetType, out currentHelper)) { throw FxTrace.Exception.AsError(new InvalidOperationException(SR.TypeConverterHelperCacheAddFailed(targetType))); } } } } object result = currentHelper.UntypedConvertFromString(stringValue, context); return(result); } return(base.ConvertFrom(context, culture, value)); }
/// <summary> /// Sets a property on an object to a value. /// </summary> /// <param name="instance">The object whose property to set.</param> /// <param name="propertyName">The name of the property to set.</param> /// <param name="value">The value to set the property to.</param> public static void SetProperty(object instance, string propertyName, object value) { if (instance == null) { throw new GeneralException(nameof(instance)); } if (propertyName == null) { throw new GeneralException(nameof(propertyName)); } var instanceType = instance.GetType(); var pi = instanceType.GetProperty(propertyName); if (pi == null) { throw new GeneralException("No property '{0}' found on the instance of type '{1}'.", propertyName, instanceType); } if (!pi.CanWrite) { throw new GeneralException("The property '{0}' on the instance of type '{1}' does not have a setter.", propertyName, instanceType); } if (value != null && !value.GetType().IsAssignableFrom(pi.PropertyType)) { value = TypeConverterHelper.To(value, pi.PropertyType); } pi.SetValue(instance, value, Array.Empty <object>()); }
public AddVariableWindow(IElement element) { InitializeComponent(); this.element = element; TypeConverterHelper.InitializeClasses(); StartPosition = FormStartPosition.Manual; Location = new Point(MainGlueWindow.MousePosition.X - this.Width / 2, System.Math.Max(0, MainGlueWindow.MousePosition.Y - Height / 2)); FillExposableVariables(); FillTunnelingObjects(); FillOverridingTypesComboBox(); FillTypeConverters(); // force set visibility radCreateNewVariable_CheckedChanged(this, null); createNewVariableViewModel = new CreateNewVariableViewModel(); createNewVariableControl1.DataContext = createNewVariableViewModel; createNewVariableViewModel.PropertyChanged += HandleCreateNewVariablePropertyChanged; FillNewVariableTypes(); }
public void GetConverter_When_Derived_From_Uri() { TypeConverterHelper.GetConverter(typeof(Uri2)) .Should() .NotBeNull() .And .BeOfType <UriTypeConverter>(); }
public void GetProperties_When_Property_Is_Overridden() { var properties = TypeConverterHelper.GetProperties(typeof(_MyClass2)); properties.Should().HaveCount(1); properties[0].Name.Should().Be(nameof(_MyClass2.ByteProperty)); properties[0].ComponentType.Should().BeSameAs(typeof(_MyClass2)); }
public void GetConverter_When_Color() { TypeConverterHelper.GetConverter(typeof(Color)) .Should() .NotBeNull() .And .BeOfType <ColorConverter>(); }
public void GetConverter_When_SolidColorBrush() { TypeConverterHelper.GetConverter(typeof(SolidColorBrush)) .Should() .NotBeNull() .And .BeOfType <BrushConverter>(); }
public void GetConverter_When_TypeConverterAttribute_4() { TypeConverterHelper.GetConverter(typeof(IMyClass4)) .Should() .NotBeNull() .And .BeOfType <IMyClass4Converter>(); }
public void GetConverter_When_TypeConverterAttribute_2() { TypeConverterHelper.GetConverter(typeof(MyClass2)) .Should() .NotBeNull() .And .BeOfType <MyClass1Converter>(); }
public void GetProperties_Inheritance_1() { var properties = TypeConverterHelper.GetProperties(typeof(_MyType1)); properties.Should().HaveCount(2); properties[nameof(_MyType1.IntProperty)].Should().NotBeNull(); properties[nameof(_MyType1.DoubleProperty)].Should().NotBeNull(); }
public void GetProperties_When_New_Property_Hides_Base_Property() { var properties = TypeConverterHelper.GetProperties(typeof(_MyType5)); properties.Should().HaveCount(1); properties[0].Name.Should().Be(nameof(_MyType5.FloatProperty)); properties[0].ComponentType.Should().BeSameAs(typeof(_MyType5)); }
public void GetConverter_When_RepeatBehavior() { TypeConverterHelper.GetConverter(typeof(RepeatBehavior)) .Should() .NotBeNull() .And .BeOfType <RepeatBehaviorConverter>(); }
public void GetConverter_When_KeyTime() { TypeConverterHelper.GetConverter(typeof(KeyTime)) .Should() .NotBeNull() .And .BeOfType <KeyTimeConverter>(); }
public void GetConverter_When_Guid() { TypeConverterHelper.GetConverter(typeof(Guid)) .Should() .NotBeNull() .And .BeOfType <GuidConverter>(); }
public static IEnumerable <string> GetConstants <TInput>() where TInput : class { return(typeof(TInput).GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy) .Where(fi => fi.IsLiteral && !fi.IsInitOnly) .Select(fi => TypeConverterHelper.To <string>(fi.GetRawConstantValue())) .ToList()); }
public void GetConverter_When_TimeSpan() { TypeConverterHelper.GetConverter(typeof(TimeSpan)) .Should() .NotBeNull() .And .BeOfType <TimeSpanConverter>(); }