public void IsPrimitiveType_ReturnsTrue_ForChar() { Assert.IsTrue(ReflectionExtensions.IsPrimitive(typeof(char))); }
public Lambda ParseAs <TDelegate>(string expressionText, params string[] parametersNames) { var delegateInfo = ReflectionExtensions.GetDelegateInfo(typeof(TDelegate), parametersNames); return(ParseAsLambda(expressionText, delegateInfo.ReturnType, delegateInfo.Parameters)); }
public virtual CompositeIdentityPart <TId> CompositeId <TId>(Expression <Func <T, TId> > memberExpression) { CompositeIdentityPart <TId> compositeIdentityPart = new CompositeIdentityPart <TId>(ReflectionExtensions.ToMember <T, TId>(memberExpression).Name); this.providers.CompositeId = (ICompositeIdMappingProvider)compositeIdentityPart; return(compositeIdentityPart); }
public async Task Handle(TEvent @event) { var isNew = false; var isStartable = typeof(ISagaStartedBy <TEvent>).GetTypeInfo().IsAssignableFrom(typeof(TSaga).GetTypeInfo()); var sagaFinder = ReflectionExtensions.ExpandType(typeof(TEvent)) .Select(x => typeof(ISagaFinder <,>).MakeGenericType(typeof(TSaga), x)) .Select(x => scope.GetServices(x).FirstOrDefault()) .Where(x => x != null) .Select(x => { var finderType = x.GetType(); var findByAsync = finderType.GetRuntimeMethods() .First(m => { var param = m.GetParameters(); return(m.Name == "FindByAsync" && param.Length == 1 && param.All(arg => arg.ParameterType.GetTypeInfo().IsAssignableFrom(typeof(TEvent).GetTypeInfo()))); }); return(new Func <TEvent, Task <TSaga> >(e => (Task <TSaga>)findByAsync.Invoke(x, new object[] { e }))); }) .FirstOrDefault(); TSaga saga; if (isStartable) { saga = await FindSaga(@event, sagaFinder); if (saga == null) { isNew = true; saga = sagaRepository.NewSaga(); } } else { saga = await FindSaga(@event, sagaFinder); if (saga == null) { throw new NoSagaFoundException(typeof(TSaga), typeof(TEvent)); } } // ReSharper disable once SuspiciousTypeConversion.Global await((IEventHandler <TEvent>)saga).Handle(@event); if (!saga.IsCompleted && isNew) { await sagaRepository.CreateAsync(saga); } else if (saga.IsCompleted) { if (!isNew) { await sagaRepository.CompleteAsync(saga); } } else { await sagaRepository.UpdateAsync(saga); } }
public static MessagePackSerializer CreateCollectionSerializer <T>( #endif // !UNITY SerializationContext context, Type targetType, CollectionTraits traits, PolymorphismSchema schema ) { var targetInfo = UnpackHelpers.DetermineCollectionSerializationStrategy(targetType, context.CompatibilityOptions.AllowAsymmetricSerializer); switch (traits.DetailedCollectionType) { case CollectionDetailedKind.Array: { return(ArraySerializer.Create <T>(context, schema)); } case CollectionDetailedKind.GenericList: #if !NETFX_35 && !UNITY case CollectionDetailedKind.GenericSet: #endif // !NETFX_35 && !UNITY case CollectionDetailedKind.GenericCollection: { return (#if !UNITY (MessagePackSerializer <T>) ReflectionExtensions.CreateInstancePreservingExceptionType <IVariantReflectionSerializerFactory>( typeof(CollectionSerializerFactory <,>).MakeGenericType(typeof(T), traits.ElementType) ).Create(context, targetType, traits, schema, targetInfo)); #else new ReflectionCollectionMessagePackSerializer(context, typeof(T), targetType, traits, schema, targetInfo); #endif // !UNITY } case CollectionDetailedKind.GenericEnumerable: { return (#if !UNITY (MessagePackSerializer <T>) ReflectionExtensions.CreateInstancePreservingExceptionType <IVariantReflectionSerializerFactory>( typeof(EnumerableSerializerFactory <,>).MakeGenericType(typeof(T), traits.ElementType) ).Create(context, targetType, traits, schema, targetInfo)); #else new ReflectionEnumerableMessagePackSerializer(context, typeof(T), targetType, traits, schema, targetInfo); #endif // !Enumerable } case CollectionDetailedKind.GenericDictionary: { var genericArgumentOfKeyValuePair = traits.ElementType.GetGenericArguments(); return (#if !UNITY (MessagePackSerializer <T>) ReflectionExtensions.CreateInstancePreservingExceptionType <IVariantReflectionSerializerFactory>( typeof(DictionarySerializerFactory <, ,>).MakeGenericType( typeof(T), genericArgumentOfKeyValuePair[0], genericArgumentOfKeyValuePair[1] ) ).Create(context, targetType, traits, schema, targetInfo)); #else new ReflectionDictionaryMessagePackSerializer( context, typeof(T), targetType, genericArgumentOfKeyValuePair[0], genericArgumentOfKeyValuePair[1], traits, schema, targetInfo ); #endif // !UNITY } case CollectionDetailedKind.NonGenericList: { return (#if !UNITY (MessagePackSerializer <T>) ReflectionExtensions.CreateInstancePreservingExceptionType <IVariantReflectionSerializerFactory>( typeof(NonGenericListSerializerFactory <>).MakeGenericType(typeof(T)) ).Create(context, targetType, traits, schema, targetInfo)); #else new ReflectionNonGenericListMessagePackSerializer(context, typeof(T), targetType, traits, schema, targetInfo); #endif // !UNITY } case CollectionDetailedKind.NonGenericCollection: { return (#if !UNITY (MessagePackSerializer <T>) ReflectionExtensions.CreateInstancePreservingExceptionType <IVariantReflectionSerializerFactory>( typeof(NonGenericCollectionSerializerFactory <>).MakeGenericType(typeof(T)) ).Create(context, targetType, traits, schema, targetInfo)); #else new ReflectionNonGenericCollectionMessagePackSerializer(context, typeof(T), targetType, traits, schema, targetInfo); #endif // !UNITY } case CollectionDetailedKind.NonGenericEnumerable: { return (#if !UNITY (MessagePackSerializer <T>) ReflectionExtensions.CreateInstancePreservingExceptionType <IVariantReflectionSerializerFactory>( typeof(NonGenericEnumerableSerializerFactory <>).MakeGenericType(typeof(T)) ).Create(context, targetType, traits, schema, targetInfo)); #else new ReflectionNonGenericEnumerableMessagePackSerializer(context, typeof(T), targetType, traits, schema, targetInfo); #endif // !UNITY } case CollectionDetailedKind.NonGenericDictionary: { return (#if !UNITY (MessagePackSerializer <T>) ReflectionExtensions.CreateInstancePreservingExceptionType <IVariantReflectionSerializerFactory>( typeof(NonGenericDictionarySerializerFactory <>).MakeGenericType(typeof(T)) ).Create(context, targetType, traits, schema, targetInfo)); #else new ReflectionNonGenericDictionaryMessagePackSerializer(context, typeof(T), targetType, traits, schema, targetInfo); #endif // !UNITY } default: { return(null); } } }
public void Reflection_MultipleMethodsImplementedException() { Assert.That(() => ReflectionExtensions.FindMethod(typeof(IReaderAB), "ReadStructBegin", new Type[0]), Throws.TypeOf <System.Reflection.AmbiguousMatchException>() .With.Message.Contains("FindMethod found more than one matching method")); }
private void InitializeListener() { _listener = ReflectionExtensions.CreateWeakEventHandler <ItemsSourceGeneratorBase, EventArgs>(this, (@base, o, arg3) => @base.OnTargetDisposed(o, arg3)); }
public StateMutator() { _mutators = ReflectionExtensions.GetStateMutators <TState>(); }
/// <summary> /// Detach dependants of entity. /// </summary> /// <exception cref="ArgumentNullException"> /// When entity is null /// </exception> /// <typeparam name="TEntity">Type of entity.</typeparam> /// <param name="entity">Entity to detach dependants.</param> /// <param name="detachItself">Also detach entity itself.</param> public void DetachWithDependants <TEntity>( TEntity entity, bool detachItself) where TEntity : class { if (entity == null) { throw new ArgumentNullException(nameof(entity)); } string typeName = entity.GetType().Name; IGraphEntityTypeManager graphEntityTypeManager = GetEntityTypeManager(typeName); List <string> dependantPropertyTypes = graphEntityTypeManager .GetForeignKeyDetails() .Where(r => r.FromDetails .ContainerClass .Equals(typeName)) .Select(r => r.ToDetails.ContainerClass) .ToList(); List <PropertyInfo> dependantProperties = entity .GetType() .GetProperties() .Where(p => dependantPropertyTypes .Contains(p.PropertyType.GetUnderlyingType().Name)) .ToList(); if (dependantProperties != null && dependantProperties.Count > 0) { foreach (PropertyInfo childEntityProperty in dependantProperties) { if (childEntityProperty.PropertyType.IsCollectionType()) { // If child entity is collection detach all entities inside this collection IEnumerable <object> enumerableChildEntity = ReflectionExtensions.GetPropertyValue(entity, childEntityProperty.Name) as IEnumerable <object>; if (enumerableChildEntity != null) { foreach (dynamic childEntity in enumerableChildEntity.ToList()) { if (childEntity != null) { DetachWithDependants(childEntity, true); } } } } else { // If child entity is not collection define state of its own dynamic childEntity = ReflectionExtensions.GetPropertyValue(entity, childEntityProperty.Name); if (childEntity != null) { DetachWithDependants(childEntity, true); } } } } if (detachItself) { Context.Entry(entity).State = EntityState.Detached; } }
public void IsPrimitiveType_ReturnsTrue_ForInt() { Assert.IsTrue(ReflectionExtensions.IsPrimitive(typeof(int))); Assert.IsTrue(ReflectionExtensions.IsPrimitive(typeof(uint))); }
public void IsPrimitiveType_ReturnsTrue_ForLong() { Assert.IsTrue(ReflectionExtensions.IsPrimitive(typeof(long))); Assert.IsTrue(ReflectionExtensions.IsPrimitive(typeof(ulong))); }
public void IsPrimitiveType_ReturnsTrue_ForFloat() { Assert.IsTrue(ReflectionExtensions.IsPrimitive(typeof(float))); }
public void IsPrimitiveType_ReturnsTrue_ForDouble() { Assert.IsTrue(ReflectionExtensions.IsPrimitive(typeof(double))); }
public void IsPrimitiveType_ReturnsTrue_ForDecimal() { Assert.IsTrue(ReflectionExtensions.IsPrimitive(typeof(decimal))); }
/// <summary> /// Производит прошивку словаря /// </summary> /// <param name="target"></param> /// <param name="source"></param> /// <param name="source2"></param> /// <param name="controlkey"></param> /// <returns></returns> public string Interpolate(string target, object source = null, IDictionary <string, object> source2 = null, string controlkey = null) { if (string.IsNullOrEmpty(target)) { return(target); } if (-1 == target.IndexOf(AncorSymbol)) { return(target); } if (-1 == target.IndexOf('{')) { return(target); } if (-1 == target.IndexOf('}')) { return(target); } //оптимизация возврата исходной строки где нет вообще контента _source2 = source2; if (string.IsNullOrWhiteSpace(target)) { return(target); } //оптимизация возврата исходной строки при отсутствии анкоров if (target.All(_ => _ != AncorSymbol)) { return(target); } if (null == source) { source = DefaultSubst; } if (source is IDictionary <string, object> ) { _source = (IDictionary <string, object>)source; } else if (source is IDictionary <string, string> ) { _source = ((IDictionary <string, string>)source).ToDictionary(_ => _.Key, GetValue); } else if (source is IEnumerable <KeyValuePair <string, object> > ) { _source = new Dictionary <string, object>(); foreach (var values in (IEnumerable <KeyValuePair <string, object> >)source) { _source[values.Key] = values.Value.ToStr(); } } else { _source = new Dictionary <string, object>(); foreach (var getval in ReflectionExtensions.FindAllValueMembers(source.GetType(), null, true, true)) { _source[getval.Member.Name] = getval.Get(source); } } _sourceString = target; _targetBuffer = new StringBuilder(); _currentBuffer = new StringBuilder(); _currentSubst = new StringBuilder(); _currentCode = new StringBuilder(); _wasAncor = false; _wasOpen = false; _controlKey = controlkey; Interpolate(); // если есть остаточное открытие - значит у нас не до конца была произведена подстановка // мы должны допотставить данные из currentBuffer if (_wasAncor && !_wasOpen) { _targetBuffer.Append(AncorSymbol); } if (_wasOpen) { StornateTail(); } return(_targetBuffer.ToString()); }
// ReSharper disable UnusedParameter.Local private static MessagePackSerializer TryCreateImmutableCollectionSerializer(SerializationContext context, Type targetType, PolymorphismSchema schema) { #if NETFX_35 || NETFX_40 || SILVERLIGHT // ImmutableCollections does not support above platforms. return(null); #else if (targetType.Namespace != "System.Collections.Immutable" && targetType.Namespace != "Microsoft.FSharp.Collections") { return(null); } if (!targetType.GetIsGenericType()) { return(null); } var itemSchema = (schema ?? PolymorphismSchema.Default); switch (DetermineImmutableCollectionType(targetType)) { case ImmutableCollectionType.ImmutableArray: case ImmutableCollectionType.ImmutableList: case ImmutableCollectionType.ImmutableHashSet: case ImmutableCollectionType.ImmutableSortedSet: case ImmutableCollectionType.ImmutableQueue: { return (ReflectionExtensions.CreateInstancePreservingExceptionType <IGenericBuiltInSerializerFactory>( typeof(ImmutableCollectionSerializerFactory <,>).MakeGenericType(targetType, targetType.GetGenericArguments()[0]) ).Create(context, itemSchema)); } case ImmutableCollectionType.ImmutableStack: { return (ReflectionExtensions.CreateInstancePreservingExceptionType <IGenericBuiltInSerializerFactory>( typeof(ImmutableStackSerializerFactory <,>).MakeGenericType(targetType, targetType.GetGenericArguments()[0]) ).Create(context, itemSchema)); } case ImmutableCollectionType.ImmutableDictionary: case ImmutableCollectionType.ImmutableSortedDictionary: { return (ReflectionExtensions.CreateInstancePreservingExceptionType <IGenericBuiltInSerializerFactory>( typeof(ImmutableDictionarySerializerFactory <, ,>).MakeGenericType(targetType, targetType.GetGenericArguments()[0], targetType.GetGenericArguments()[1]) ).Create(context, itemSchema)); } case ImmutableCollectionType.FSharpList: { return (ReflectionExtensions.CreateInstancePreservingExceptionType <IGenericBuiltInSerializerFactory>( typeof(FSharpCollectionSerializerFactory <,>).MakeGenericType(targetType, targetType.GetGenericArguments()[0]), "ListModule" ).Create(context, itemSchema)); } case ImmutableCollectionType.FSharpSet: { return (ReflectionExtensions.CreateInstancePreservingExceptionType <IGenericBuiltInSerializerFactory>( typeof(FSharpCollectionSerializerFactory <,>).MakeGenericType(targetType, targetType.GetGenericArguments()[0]), "SetModule" ).Create(context, itemSchema)); } case ImmutableCollectionType.FSharpMap: { return (ReflectionExtensions.CreateInstancePreservingExceptionType <IGenericBuiltInSerializerFactory>( typeof(FSharpMapSerializerFactory <, ,>).MakeGenericType(targetType, targetType.GetGenericArguments()[0], targetType.GetGenericArguments()[1]) ).Create(context, itemSchema)); } default: { #if DEBUG Contract.Assert(false, "Unknown type:" + targetType); #endif // DEBUG // ReSharper disable HeuristicUnreachableCode return(null); // ReSharper restore HeuristicUnreachableCode } } #endif // NETFX_35 || NETFX_40 || SILVERLIGHT }
public void Reflection_FindMethodFromInterface() { Assert.AreEqual("ReadStructBegin", ReflectionExtensions.FindMethod(typeof(IReaderA), "ReadStructBegin", new Type[0]).Name); Assert.AreEqual(typeof(IReaderA), ReflectionExtensions.FindMethod(typeof(IReaderA), "ReadStructBegin", new Type[0]).DeclaringType); }
private void OnCopyTableData() { if (!ReportInfoCollection.Any()) { return; } StringBuilder builder = new StringBuilder(); // Header var displayNameGame = ReflectionExtensions.GetPropertyDisplayName <ReportInfo>(x => x.Game); var displayNameResolution = ReflectionExtensions.GetPropertyDisplayName <ReportInfo>(x => x.Resolution); var displayNameDate = ReflectionExtensions.GetPropertyDisplayName <ReportInfo>(x => x.Date); var displayNameTime = ReflectionExtensions.GetPropertyDisplayName <ReportInfo>(x => x.Time); var displayNameNumberOfSamples = ReflectionExtensions.GetPropertyDisplayName <ReportInfo>(x => x.NumberOfSamples); var displayNameRecordTime = ReflectionExtensions.GetPropertyDisplayName <ReportInfo>(x => x.RecordTime); var displayNameCpu = ReflectionExtensions.GetPropertyDisplayName <ReportInfo>(x => x.Cpu); var displayNameGraphicCard = ReflectionExtensions.GetPropertyDisplayName <ReportInfo>(x => x.GraphicCard); var displayNameRam = ReflectionExtensions.GetPropertyDisplayName <ReportInfo>(x => x.Ram); var displayNameMaxFps = ReflectionExtensions.GetPropertyDisplayName <ReportInfo>(x => x.MaxFps); var displayNameNinetyNinePercentQuantileFps = ReflectionExtensions.GetPropertyDisplayName <ReportInfo>(x => x.NinetyNinePercentQuantileFps); var displayNameNinetyFivePercentQuantileFps = ReflectionExtensions.GetPropertyDisplayName <ReportInfo>(x => x.NinetyFivePercentQuantileFps); var displayNameAverageFps = ReflectionExtensions.GetPropertyDisplayName <ReportInfo>(x => x.AverageFps); var displayNameMedianFps = ReflectionExtensions.GetPropertyDisplayName <ReportInfo>(x => x.MedianFps); var displayNameFivePercentQuantileFps = ReflectionExtensions.GetPropertyDisplayName <ReportInfo>(x => x.FivePercentQuantileFps); var displayNameOnePercentQuantileFps = ReflectionExtensions.GetPropertyDisplayName <ReportInfo>(x => x.OnePercentQuantileFps); var displayNameOnePercentLowAverageFps = ReflectionExtensions.GetPropertyDisplayName <ReportInfo>(x => x.OnePercentLowAverageFps); var displayNameZeroDotTwoPercentQuantileFps = ReflectionExtensions.GetPropertyDisplayName <ReportInfo>(x => x.ZeroDotTwoPercentQuantileFps); var displayNameZeroDotOnePercentQuantileFps = ReflectionExtensions.GetPropertyDisplayName <ReportInfo>(x => x.ZeroDotOnePercentQuantileFps); var displayNameZeroDotOnePercentLowAverageFps = ReflectionExtensions.GetPropertyDisplayName <ReportInfo>(x => x.ZeroDotOnePercentLowAverageFps); var displayNameMinFps = ReflectionExtensions.GetPropertyDisplayName <ReportInfo>(x => x.MinFps); var displayNameAdaptiveSTDFps = ReflectionExtensions.GetPropertyDisplayName <ReportInfo>(x => x.AdaptiveSTDFps); var displayNameCpuFpsPerWatt = ReflectionExtensions.GetPropertyDisplayName <ReportInfo>(x => x.CpuFpsPerWatt); //var displayNameGpuFpsPerWatt = ReflectionExtensions.GetPropertyDisplayName<ReportInfo>(x => x.GpuFpsPerWatt); var displayNameCustomComment = ReflectionExtensions.GetPropertyDisplayName <ReportInfo>(x => x.CustomComment); builder.Append(displayNameGame + "\t" + displayNameResolution + "\t" + displayNameDate + "\t" + displayNameTime + "\t" + displayNameNumberOfSamples + "\t" + displayNameRecordTime + "\t" + displayNameCpu + "\t" + displayNameGraphicCard + "\t" + displayNameRam + "\t" + displayNameMaxFps + "\t" + displayNameNinetyNinePercentQuantileFps + "\t" + displayNameNinetyFivePercentQuantileFps + "\t" + displayNameAverageFps + "\t" + displayNameMedianFps + "\t" + displayNameFivePercentQuantileFps + "\t" + displayNameOnePercentQuantileFps + "\t" + displayNameOnePercentLowAverageFps + "\t" + displayNameZeroDotTwoPercentQuantileFps + "\t" + displayNameZeroDotOnePercentQuantileFps + "\t" + displayNameZeroDotOnePercentLowAverageFps + "\t" + displayNameMinFps + "\t" + displayNameAdaptiveSTDFps + "\t" + displayNameCpuFpsPerWatt + "\t" + //displayNameGpuFpsPerWatt + "\t" + displayNameCustomComment + Environment.NewLine); var cultureInfo = CultureInfo.CurrentCulture; foreach (var reportInfo in ReportInfoCollection) { builder.Append(reportInfo.Game + "\t" + reportInfo.Resolution + "\t" + reportInfo.Date.ToString(cultureInfo) + "\t" + reportInfo.Time.ToString(cultureInfo) + "\t" + reportInfo.NumberOfSamples + "\t" + reportInfo.RecordTime.ToString(cultureInfo) + "\t" + reportInfo.Cpu + "\t" + reportInfo.GraphicCard + "\t" + reportInfo.Ram + "\t" + reportInfo.MaxFps.ToString(cultureInfo) + "\t" + reportInfo.NinetyNinePercentQuantileFps.ToString(cultureInfo) + "\t" + reportInfo.NinetyFivePercentQuantileFps.ToString(cultureInfo) + "\t" + reportInfo.AverageFps.ToString(cultureInfo) + "\t" + reportInfo.MedianFps.ToString(cultureInfo) + "\t" + reportInfo.FivePercentQuantileFps.ToString(cultureInfo) + "\t" + reportInfo.OnePercentQuantileFps.ToString(cultureInfo) + "\t" + reportInfo.OnePercentLowAverageFps.ToString(cultureInfo) + "\t" + reportInfo.ZeroDotTwoPercentQuantileFps.ToString(cultureInfo) + "\t" + reportInfo.ZeroDotOnePercentQuantileFps.ToString(cultureInfo) + "\t" + reportInfo.ZeroDotOnePercentLowAverageFps.ToString(cultureInfo) + "\t" + reportInfo.MinFps.ToString(cultureInfo) + "\t" + reportInfo.AdaptiveSTDFps.ToString(cultureInfo) + "\t" + reportInfo.CpuFpsPerWatt.ToString(cultureInfo) + "\t" + //reportInfo.GpuFpsPerWatt.ToString(cultureInfo) + "\t" + reportInfo.CustomComment + Environment.NewLine); } Clipboard.SetDataObject(builder.ToString(), false); }
protected ItemsSourceGeneratorBase() { _handler = ReflectionExtensions.MakeWeakCollectionChangedHandler(this, (@base, o, arg3) => @base.OnCollectionChanged(arg3)); }
public Type GetComponentType() { return(ReflectionExtensions.GetTypeFromAssemblyQualifiedTypeName(this.AssemblyQualifiedTypeName)); }
public static object NullValueType(Type type) { return(ReflectionExtensions.GetDefaultValue(type)); }
protected override void OnInitialized(IValidatorContext context) { _weakHandler = ReflectionExtensions.MakeWeakErrorsChangedHandler(this, ViewModelErrorsChanged); Instance.ErrorsChanged += _weakHandler; }
internal static IMessagePackSingleObjectSerializer TryCreateAbstractCollectionSerializer(SerializationContext context, Type abstractType, Type concreteType, PolymorphismSchema schema, CollectionTraits traits) { switch (traits.DetailedCollectionType) { case CollectionDetailedKind.GenericList: #if !NETFX_35 && !UNITY case CollectionDetailedKind.GenericSet: #endif // !NETFX_35 && !UNITY case CollectionDetailedKind.GenericCollection: { #if !UNITY return (ReflectionExtensions.CreateInstancePreservingExceptionType <IVariantSerializerFactory>( typeof(CollectionSerializerFactory <,>).MakeGenericType(abstractType, traits.ElementType) ).Create(context, concreteType, schema)); #else return(new AbstractCollectionMessagePackSerializer(context, abstractType, concreteType, traits, schema)); #endif } #if !NETFX_35 && !UNITY && !NETFX_40 && !(SILVERLIGHT && !WINDOWS_PHONE) case CollectionDetailedKind.GenericReadOnlyList: case CollectionDetailedKind.GenericReadOnlyCollection: { #if !UNITY return (ReflectionExtensions.CreateInstancePreservingExceptionType <IVariantSerializerFactory>( typeof(ReadOnlyCollectionSerializerFactory <,>).MakeGenericType(abstractType, traits.ElementType) ).Create(context, concreteType, schema)); #else return(new AbstractCollectionMessagePackSerializer(context, abstractType, concreteType, traits, schema)); #endif } #endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) case CollectionDetailedKind.GenericEnumerable: { #if !UNITY return (ReflectionExtensions.CreateInstancePreservingExceptionType <IVariantSerializerFactory>( typeof(EnumerableSerializerFactory <,>).MakeGenericType(abstractType, traits.ElementType) ).Create(context, concreteType, schema)); #else return(new AbstractEnumerableMessagePackSerializer(context, abstractType, concreteType, traits, schema)); #endif } case CollectionDetailedKind.GenericDictionary: { var genericArgumentOfKeyValuePair = traits.ElementType.GetGenericArguments(); #if !UNITY return (ReflectionExtensions.CreateInstancePreservingExceptionType <IVariantSerializerFactory>( typeof(DictionarySerializerFactory <, ,>).MakeGenericType( abstractType, genericArgumentOfKeyValuePair[0], genericArgumentOfKeyValuePair[1] ) ).Create(context, concreteType, schema)); #else return(new AbstractDictionaryMessagePackSerializer(context, abstractType, concreteType, genericArgumentOfKeyValuePair[0], genericArgumentOfKeyValuePair[1], traits, schema)); #endif } #if !NETFX_35 && !UNITY && !NETFX_40 && !(SILVERLIGHT && !WINDOWS_PHONE) case CollectionDetailedKind.GenericReadOnlyDictionary: { var genericArgumentOfKeyValuePair = traits.ElementType.GetGenericArguments(); #if !UNITY return (ReflectionExtensions.CreateInstancePreservingExceptionType <IVariantSerializerFactory>( typeof(ReadOnlyDictionarySerializerFactory <, ,>).MakeGenericType( abstractType, genericArgumentOfKeyValuePair[0], genericArgumentOfKeyValuePair[1] ) ).Create(context, concreteType, schema)); #else return(new AbstractDictionaryMessagePackSerializer(context, abstractType, concreteType, genericArgumentOfKeyValuePair[0], genericArgumentOfKeyValuePair[1], traits, schema)); #endif } #endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) case CollectionDetailedKind.NonGenericList: { #if !UNITY return (ReflectionExtensions.CreateInstancePreservingExceptionType <IVariantSerializerFactory>( typeof(NonGenericListSerializerFactory <>).MakeGenericType(abstractType) ).Create(context, concreteType, schema)); #else return(new AbstractNonGenericListMessagePackSerializer(context, abstractType, concreteType, schema)); #endif } case CollectionDetailedKind.NonGenericCollection: { #if !UNITY return (ReflectionExtensions.CreateInstancePreservingExceptionType <IVariantSerializerFactory>( typeof(NonGenericCollectionSerializerFactory <>).MakeGenericType(abstractType) ).Create(context, concreteType, schema)); #else return(new AbstractNonGenericCollectionMessagePackSerializer(context, abstractType, concreteType, schema)); #endif } case CollectionDetailedKind.NonGenericEnumerable: { #if !UNITY return (ReflectionExtensions.CreateInstancePreservingExceptionType <IVariantSerializerFactory>( typeof(NonGenericEnumerableSerializerFactory <>).MakeGenericType(abstractType) ).Create(context, concreteType, schema)); #else return(new AbstractNonGenericEnumerableMessagePackSerializer(context, abstractType, concreteType, schema)); #endif } case CollectionDetailedKind.NonGenericDictionary: { #if !UNITY return (ReflectionExtensions.CreateInstancePreservingExceptionType <IVariantSerializerFactory>( typeof(NonGenericDictionarySerializerFactory <>).MakeGenericType(abstractType) ).Create(context, concreteType, schema)); #else return(new AbstractNonGenericDictionaryMessagePackSerializer(context, abstractType, concreteType, schema)); #endif } default: { return(null); } } }
// Automatic Conversion of TiledObjects in a .tmx file to TeeEngine Entities using C# Reflection. private void ConvertMapObjects(TiledMap map) { foreach (TiledObjectLayer objectLayer in map.TiledObjectLayers) { foreach (TiledObject tiledObject in objectLayer.TiledObjects) { Entity entity = null; // Special (Static) Tiled-Object when a Gid is specified. if (tiledObject.Type == null && tiledObject.Gid != -1) { Tile sourceTile = map.Tiles[tiledObject.Gid]; entity = new Entity(); entity.Drawables.Add("standard", sourceTile); entity.CurrentDrawableState = "standard"; entity.Pos = new Vector2(tiledObject.X, tiledObject.Y); // Cater for any difference in origin from Tiled's default Draw Origin of (0,1). entity.Pos.X += (sourceTile.Origin.X - 0.0f) * sourceTile.GetSourceRectangle(0).Width; entity.Pos.Y += (sourceTile.Origin.Y - 1.0f) * sourceTile.GetSourceRectangle(0).Height; } else if (tiledObject.Type != null) { // Try and load Entity types from both the Assembly specified in MapProperties and within the GameEngine. Assembly userAssembly = (map.HasProperty("Assembly")) ? Assembly.Load(map.GetProperty("Assembly")) : null; Assembly engineAssembly = Assembly.GetExecutingAssembly(); // Try for user Assembly first - allows default Objects to be overriden if absoluately necessary. object createdObject = null; if (userAssembly != null) { createdObject = userAssembly.CreateInstance(tiledObject.Type); } if (createdObject == null) { createdObject = engineAssembly.CreateInstance(tiledObject.Type); } if (createdObject == null) { throw new ArgumentException(string.Format("'{0}' does not exist in any of the loaded Assemblies", tiledObject.Type)); } if (createdObject is Entity) { // Convert to Entity object and assign values. entity = (Entity)createdObject; entity.Pos = new Vector2(tiledObject.X, tiledObject.Y); // If the entity implements the ISizedEntity interface, apply Width and Height. if (entity is ISizedEntity) { ((ISizedEntity)entity).Width = tiledObject.Width; ((ISizedEntity)entity).Height = tiledObject.Height; } if (entity is IPolygonEntity) { ((IPolygonEntity)entity).Points = tiledObject.Points; } foreach (string propertyKey in tiledObject.PropertyKeys) { // Ignore all properties starting with '.' if (propertyKey.StartsWith(".")) { continue; } // Bind Events. if (propertyKey.StartsWith("$")) { string methodName = tiledObject.GetProperty(propertyKey); string eventName = propertyKey.Substring(1, propertyKey.Length - 1); MethodInfo methodInfo = MapScript.GetType().GetMethod(methodName); EventInfo eventInfo = entity.GetType().GetEvent(eventName); Delegate delegateMethod = Delegate.CreateDelegate(eventInfo.EventHandlerType, MapScript, methodInfo); eventInfo.AddEventHandler(entity, delegateMethod); } else { // Bind Properties. ReflectionExtensions.SmartSetProperty(entity, propertyKey, tiledObject.GetProperty(propertyKey)); } } } else { throw new ArgumentException(string.Format("'{0}' is not an Entity object", tiledObject.Type)); } } if (entity != null) { this.AddEntity(tiledObject.Name, entity); } } } }
public ItemsSourceTableViewSource([NotNull] UITableView tableView, string itemTemplate = AttachedMemberConstants.ItemTemplate) : base(tableView, itemTemplate) { _weakHandler = ReflectionExtensions.MakeWeakCollectionChangedHandler(this, (adapter, o, arg3) => adapter.OnCollectionChanged(o, arg3)); }
public static IMemberInfo FindMember <T>(this ITypeInfo typesInfo, Expression <Func <T, object> > expression) { MemberInfo memberInfo = ReflectionExtensions.GetExpression(expression); return(typesInfo.FindMember(memberInfo.Name)); }
public static T CreateInstance <T>() { return((T)ReflectionExtensions.CreateInstance <T>()); }
internal static object StringToType( Type type, string strType, EmptyCtorDelegate ctorFn, Dictionary <string, TypeAccessor> typeAccessorMap) { var index = 0; if (strType == null) { return(null); } //if (!Serializer.EatMapStartChar(strType, ref index)) for (; index < strType.Length; index++) { var c = strType[index]; if (c >= JsonTypeSerializer.WhiteSpaceFlags.Length || !JsonTypeSerializer.WhiteSpaceFlags[c]) { break; } } //Whitespace inline if (strType[index++] != JsWriter.MapStartChar) { throw DeserializeTypeRef.CreateSerializationError(type, strType); } if (strType == JsWriter.EmptyMap) { return(ctorFn()); } object instance = null; var strTypeLength = strType.Length; while (index < strTypeLength) { var propertyName = JsonTypeSerializer.ParseJsonString(strType, ref index); //Serializer.EatMapKeySeperator(strType, ref index); for (; index < strType.Length; index++) { var c = strType[index]; if (c >= JsonTypeSerializer.WhiteSpaceFlags.Length || !JsonTypeSerializer.WhiteSpaceFlags[c]) { break; } } //Whitespace inline if (strType.Length != index) { index++; } var propertyValueStr = Serializer.EatValue(strType, ref index); var possibleTypeInfo = propertyValueStr != null && propertyValueStr.Length > 1 && propertyValueStr[0] == '_'; if (possibleTypeInfo && propertyName == JsWriter.TypeAttr) { var typeName = Serializer.ParseString(propertyValueStr); instance = ReflectionExtensions.CreateInstance(typeName); if (instance == null) { Tracer.Instance.WriteWarning("Could not find type: " + propertyValueStr); } else { //If __type info doesn't match, ignore it. if (!type.GetTypeInfo().IsInstanceOfType(instance)) { instance = null; } } Serializer.EatItemSeperatorOrMapEndChar(strType, ref index); continue; } if (instance == null) { instance = ctorFn(); } TypeAccessor typeAccessor; typeAccessorMap.TryGetValue(propertyName, out typeAccessor); var propType = possibleTypeInfo ? TypeAccessor.ExtractType(Serializer, propertyValueStr) : null; if (propType != null) { try { if (typeAccessor != null) { //var parseFn = Serializer.GetParseFn(propType); var parseFn = JsonReader.GetParseFn(propType); var propertyValue = parseFn(propertyValueStr); typeAccessor.SetProperty(instance, propertyValue); } //Serializer.EatItemSeperatorOrMapEndChar(strType, ref index); for (; index < strType.Length; index++) { var c = strType[index]; if (c >= JsonTypeSerializer.WhiteSpaceFlags.Length || !JsonTypeSerializer.WhiteSpaceFlags[c]) { break; } } //Whitespace inline if (index != strType.Length) { var success = strType[index] == JsWriter.ItemSeperator || strType[index] == JsWriter.MapEndChar; index++; if (success) { for (; index < strType.Length; index++) { var c = strType[index]; if (c >= JsonTypeSerializer.WhiteSpaceFlags.Length || !JsonTypeSerializer.WhiteSpaceFlags[c]) { break; } } //Whitespace inline } } continue; } catch (Exception e) when(!(e is JsonSerializationException)) { Tracer.Instance.WriteWarning("WARN: failed to set dynamic property {0} with: {1}", propertyName, propertyValueStr); } } if (typeAccessor != null && typeAccessor.GetProperty != null && typeAccessor.SetProperty != null) { try { var propertyValue = typeAccessor.GetProperty(propertyValueStr); typeAccessor.SetProperty(instance, propertyValue); } catch (Exception e) when(!(e is JsonSerializationException)) { Tracer.Instance.WriteWarning("WARN: failed to set property {0} with: {1}", propertyName, propertyValueStr); } } //Serializer.EatItemSeperatorOrMapEndChar(strType, ref index); for (; index < strType.Length; index++) { var c = strType[index]; if (c >= JsonTypeSerializer.WhiteSpaceFlags.Length || !JsonTypeSerializer.WhiteSpaceFlags[c]) { break; } } //Whitespace inline if (index != strType.Length) { var success = strType[index] == JsWriter.ItemSeperator || strType[index] == JsWriter.MapEndChar; index++; if (success) { for (; index < strType.Length; index++) { var c = strType[index]; if (c >= JsonTypeSerializer.WhiteSpaceFlags.Length || !JsonTypeSerializer.WhiteSpaceFlags[c]) { break; } } //Whitespace inline } } } return(instance); }
public VersionPart Version(Expression <Func <T, object> > memberExpression) { return(this.Version(ReflectionExtensions.ToMember <T, object>(memberExpression))); }
public void IsPrimitiveType_ReturnsTrue_ForBoolean() { Assert.IsTrue(ReflectionExtensions.IsPrimitive(typeof(bool))); }