Beispiel #1
0
        private static CollectionAdapterModel CreateCollectionAdapterModel()
        {
            var cam = new CollectionAdapterModel();

            var config    = TypeAdapterConfig <TSource, TDestination> .Configuration;
            var hasConfig = config != null;

            var sourceElementType      = ReflectionUtils.ExtractElementType(typeof(TSource));
            var destinationElementType = typeof(TDestinationElementType);

            if (ReflectionUtils.IsPrimitive(destinationElementType) || destinationElementType == typeof(object))
            {
                cam.IsPrimitive = true;

                var converter = ReflectionUtils.CreatePrimitiveConverter(sourceElementType, destinationElementType);
                if (converter != null)
                {
                    cam.AdaptInvoker = converter;
                }
            }
            else if (ReflectionUtils.IsCollection(destinationElementType))
            {
                var methodInfo = typeof(CollectionAdapter <, ,>).MakeGenericType(sourceElementType, ReflectionUtils.ExtractElementType(destinationElementType), destinationElementType).GetMethod("Adapt", new Type[] { sourceElementType, typeof(Dictionary <,>).MakeGenericType(typeof(int), typeof(int)) });
                cam.AdaptInvoker = FastInvoker.GetMethodInvoker(methodInfo);
            }
            else
            {
                var methodInfo = typeof(ClassAdapter <,>).MakeGenericType(sourceElementType, destinationElementType).GetMethod("Adapt", new Type[] { sourceElementType, typeof(Dictionary <,>).MakeGenericType(typeof(int), typeof(int)) });
                cam.AdaptInvoker = FastInvoker.GetMethodInvoker(methodInfo);
            }

            return(cam);
        }
Beispiel #2
0
        private static CollectionAdapterModel CreateCollectionAdapterModel()
        {
            var cam = new CollectionAdapterModel();

            var sourceElementType      = typeof(TSource).ExtractCollectionType();
            var destinationElementType = typeof(TDestinationElement);

            if (destinationElementType.IsPrimitiveRoot() || destinationElementType == typeof(object))
            {
                cam.IsPrimitive = true;

                var converter = sourceElementType.CreatePrimitiveConverter(destinationElementType);
                if (converter != null)
                {
                    cam.AdaptInvoker = converter;
                }
            }
            else if (destinationElementType.IsCollection())
            {
                var methodInfo = typeof(CollectionAdapter <, , ,>)
                                 .MakeGenericType(sourceElementType.ExtractCollectionType(), sourceElementType, destinationElementType.ExtractCollectionType(), destinationElementType)
                                 .GetMethod("Adapt", new[] { sourceElementType, typeof(bool), typeof(Dictionary <,>).MakeGenericType(typeof(long), typeof(int)) });
                cam.AdaptInvoker = FastInvoker.GetMethodInvoker(methodInfo);
            }
            else
            {
                var methodInfo = typeof(ClassAdapter <,>)
                                 .MakeGenericType(sourceElementType, destinationElementType)
                                 .GetMethod("Adapt", new[] { sourceElementType, typeof(bool), typeof(Dictionary <,>).MakeGenericType(typeof(long), typeof(int)) });

                cam.AdaptInvoker = FastInvoker.GetMethodInvoker(methodInfo);
            }

            return(cam);
        }
 static bool Prepare()
 {
     IsStartedSetter = Accessors.CreateSetter <KingdomTask, bool>("IsStarted");
     StartedOnSetter = Accessors.CreateSetter <KingdomTask, int>("StartedOn");
     OnTaskChanged   = Accessors.CreateInvoker <KingdomTask, object>("OnTaskChanged");
     return(true);
 }
Beispiel #4
0
        private static bool FlattenMethod(Type sourceType, MemberInfo destinationMember, Func <object> propertyModelFactory,
                                          List <PropertyModel <TSource, TDestination> > properties, IDictionary <Type, Func <object, object> > destinationTransforms)
        {
            var getMethod = sourceType.GetMethod(String.Concat("Get", destinationMember.Name));

            if (getMethod != null)
            {
                var setter = PropertyCaller <TDestination> .CreateSetMethod((PropertyInfo)destinationMember);

                if (setter == null)
                {
                    return(true);
                }

                var propertyModel = (PropertyModel <TSource, TDestination>)propertyModelFactory();
                propertyModel.ConvertType        = 2;
                propertyModel.Setter             = setter;
                propertyModel.SetterPropertyName = ExtractPropertyName(setter, "Set");
                var destinationPropertyType = typeof(TDestination);
                if (destinationTransforms.ContainsKey(destinationPropertyType))
                {
                    propertyModel.DestinationTransform = destinationTransforms[destinationPropertyType];
                }
                propertyModel.AdaptInvoker = FastInvoker.GetMethodInvoker(getMethod);

                properties.Add(propertyModel);

                return(true);
            }
            return(false);
        }
        public virtual Task InvokeAsync <TMessage>(
            ConsumerDescriptor descriptor,
            IConsumer consumer,
            ConsumeContext <TMessage> envelope,
            CancellationToken cancelToken = default) where TMessage : class
        {
            var d           = descriptor;
            var p           = descriptor.WithEnvelope ? (object)envelope : envelope.Message;
            var fastInvoker = FastInvoker.GetInvoker(d.Method);
            var ct          = cancelToken;

            Task task;

            if (d.IsAsync && !d.FireForget)
            {
                // The all async case.
                ct   = _asyncRunner.CreateCompositeCancellationToken(cancelToken);
                task = ((Task)InvokeCore(null, ct));
                task.ContinueWith(t =>
                {
                    if (t.IsFaulted)
                    {
                        HandleException(t.Exception, d);
                    }
                }, TaskContinuationOptions.None);
            }
            else if (d.FireForget)
            {
                // Sync or Async without await. Needs new dependency scope.
                task = d.IsAsync
                    ? _asyncRunner.RunTask((scope, ct) => ((Task)InvokeCore(scope, ct)))
                    : _asyncRunner.Run((scope, ct) => InvokeCore(scope, ct));
                task.ConfigureAwait(false);
            }
            else
            {
                // The all sync case
                try
                {
                    InvokeCore(null, ct);
                }
                catch (Exception ex)
                {
                    HandleException(ex, d);
                }

                task = Task.CompletedTask;
            }

            return(task);

            object InvokeCore(IComponentContext c = null, CancellationToken cancelToken = default)
Beispiel #6
0
        private static FastInvokeHandler GetAdapter(Type sourceType, Type destinationType, bool hasDestination = false)
        {
            FastInvokeHandler adapter;

            if (_cache.TryGetValue(ReflectionUtils.GetHashKey(sourceType, destinationType) * (hasDestination ? -1 : 1), out adapter))
            {
                return(adapter);
            }

            lock (_cacheLock)
            {
                long hashCode = ReflectionUtils.GetHashKey(sourceType, destinationType) * (hasDestination ? -1 : 1);

                if (_cache.TryGetValue(hashCode, out adapter))
                {
                    return(adapter);
                }

                Type[] arguments = hasDestination ? new[] { sourceType, destinationType } : new[] { sourceType };

                FastInvokeHandler invoker;

                if (sourceType.IsPrimitiveRoot() && destinationType.IsPrimitiveRoot())
                {
                    invoker = FastInvoker.GetMethodInvoker(
                        typeof(PrimitiveAdapter <,>).MakeGenericType(sourceType, destinationType)
                        .GetMethod("Adapt", arguments));
                }
                else if (sourceType.IsCollection() && destinationType.IsCollection())
                {
                    invoker = FastInvoker.GetMethodInvoker(
                        typeof(CollectionAdapter <, , ,>).MakeGenericType(sourceType.ExtractCollectionType(), sourceType,
                                                                          destinationType.ExtractCollectionType(), destinationType)
                        .GetMethod("Adapt", arguments));
                }
                else
                {
                    invoker = FastInvoker.GetMethodInvoker(
                        typeof(ClassAdapter <,>).MakeGenericType(sourceType, destinationType)
                        .GetMethod("Adapt", arguments));
                }

                _cache.Add(hashCode, invoker);
                return(invoker);
            }
        }
Beispiel #7
0
        // ReSharper restore StaticFieldInGenericType

        static CsvMarketDataSerializer()
        {
            _timeFormat = GetTimeFormat();

            if (typeof(TData) == typeof(ExecutionMessage) || typeof(TData).IsSubclassOf(typeof(CandleMessage)))
            {
                _setSecurityId = MemberProxy.Create(typeof(TData), "SecurityId");
            }

            if (typeof(TData) == typeof(ExecutionMessage))
            {
                _setExecutionType = MemberProxy.Create(typeof(TData), "ExecutionType");
            }

            _ctor = FastInvoker <VoidType, VoidType, TData> .Create(typeof(TData).GetMember <ConstructorInfo>());

            _dateMember = MemberProxy.Create(typeof(TData),
                                             typeof(TData).IsSubclassOf(typeof(CandleMessage)) ? "OpenTime" : "ServerTime");
        }
        private static FastInvokeHandler GetAdapter(Type sourceType, Type destinationType, bool hasDestination = false)
        {
            var key = sourceType.FullName + destinationType.FullName;

            if (_cache.ContainsKey(key))
            {
                return(_cache[key]);
            }
            lock (_cache)
            {
                if (_cache.ContainsKey(key))
                {
                    return(_cache[key]);
                }

                var arguments = hasDestination ? new[] { sourceType, destinationType } : new[] { sourceType };

                FastInvokeHandler invoker = null;

                if (ReflectionUtils.IsPrimitive(sourceType) && ReflectionUtils.IsPrimitive(destinationType))
                {
                    invoker = FastInvoker.GetMethodInvoker(typeof(PrimitiveAdapter <,>)
                                                           .MakeGenericType(sourceType, destinationType).GetMethod("Adapt", arguments));
                }
                else if (ReflectionUtils.IsCollection(sourceType) && ReflectionUtils.IsCollection(destinationType))
                {
                    invoker = FastInvoker.GetMethodInvoker(typeof(CollectionAdapter <, ,>)
                                                           .MakeGenericType(sourceType, ReflectionUtils.ExtractElementType(destinationType),
                                                                            destinationType).GetMethod("Adapt", arguments));
                }
                else
                {
                    invoker = FastInvoker.GetMethodInvoker(typeof(ClassAdapter <,>)
                                                           .MakeGenericType(sourceType, destinationType).GetMethod("Adapt", arguments));
                }

                _cache.Add(key, invoker);
                return(invoker);
            }
        }
        // ReSharper restore StaticFieldInGenericType

        static CsvMarketDataSerializer()
        {
            var isCandles = typeof(TData).IsCandleMessage();

            if (typeof(TData) == typeof(ExecutionMessage) || isCandles)
            {
                _setSecurityId = MemberProxy.Create(typeof(TData), "SecurityId");
            }

            if (typeof(TData) == typeof(ExecutionMessage))
            {
                _setExecutionType = MemberProxy.Create(typeof(TData), "ExecutionType");
            }

            if (isCandles)
            {
                _setCandleArg = MemberProxy.Create(typeof(TData), "Arg");
            }

            _ctor = FastInvoker <VoidType, VoidType, TData> .Create(typeof(TData).GetMember <ConstructorInfo>());

            _dateMember = MemberProxy.Create(typeof(TData), isCandles ? "OpenTime" : "ServerTime");
        }
 static bool Prepare()
 {
     DestroySheathModelInvoker = Accessors.CreateInvoker <UnitViewHandSlotData, object>("DestroySheathModel");
     return(true);
 }
Beispiel #11
0
        public void Invoke <TMessage>(ConsumerDescriptor descriptor, IConsumer consumer, ConsumeContext <TMessage> envelope) where TMessage : class
        {
            var d           = descriptor;
            var p           = descriptor.WithEnvelope ? (object)envelope : envelope.Message;
            var fastInvoker = FastInvoker.GetInvoker(d.Method);

            if (!d.FireForget && !d.IsAsync)
            {
                // The all synch case
                try
                {
                    InvokeCore();
                }
                catch (Exception ex)
                {
                    HandleException(ex, d);
                }
            }
            else if (!d.FireForget && d.IsAsync)
            {
                //// The awaitable Task case
                //BeginInvoke((Task)InvokeCore(cancelToken: AsyncRunner.AppShutdownCancellationToken), EndInvoke, d);

                // For now we must go with the AsyncRunner, the above call to BeginInvoke (APM > TPL) does not always
                // guarantee that the task is awaited and throws exceptions especially when EF is involved.
                using (var runner = AsyncRunner.Create())
                {
                    try
                    {
                        runner.Run((Task)InvokeCore(cancelToken: AsyncRunner.AppShutdownCancellationToken));
                    }
                    catch (Exception ex)
                    {
                        HandleException(ex, d);
                    }
                }
            }
            else if (d.FireForget && !d.IsAsync)
            {
                // A synch method should be executed async (without awaiting)
                AsyncRunner.Run((c, ct, state) => InvokeCore(c, ct), d)
                .ContinueWith(t => EndInvoke(t), /*TaskContinuationOptions.OnlyOnFaulted*/ TaskContinuationOptions.None)
                .ConfigureAwait(false);
            }
            else if (d.FireForget && d.IsAsync)
            {
                // An async (Task) method should be executed without awaiting
                AsyncRunner.Run((c, ct) => (Task)InvokeCore(c, ct), d)
                .ContinueWith(t => EndInvoke(t), TaskContinuationOptions.OnlyOnFaulted)
                .ConfigureAwait(false);
            }

            object InvokeCore(IComponentContext c = null, CancellationToken cancelToken = default(CancellationToken))
            {
                if (d.Parameters.Length == 0)
                {
                    // Only one method param: the message!
                    return(fastInvoker.Invoke(consumer, p));
                }

                var parameters = new object[d.Parameters.Length + 1];

                parameters[0] = p;

                int i = 0;

                foreach (var obj in ResolveParameters(c, d, cancelToken).ToArray())
                {
                    i++;
                    parameters[i] = obj;
                }

                return(fastInvoker.Invoke(consumer, parameters));
            }
        }
 static bool Prepare()
 {
     SetColor = Accessors.CreateInvoker(TargetType(), "SetColor", typeof(object), typeof(BlueprintSettlementBuilding), typeof(SettlementBuilding), typeof(SettlementState));
     return(true);
 }
 static bool Prepare()
 {
     CanBuildByLevel = Accessors.CreateInvoker <SettlementState, BlueprintSettlementBuilding, bool>("CanBuildByLevel");
     return(true);
 }
        private static AdapterModel <TSource, TDestination> CreateAdapterModel()
        {
            var fieldModelFactory    = FastObjectFactory.CreateObjectFactory <FieldModel>();
            var propertyModelFactory = FastObjectFactory.CreateObjectFactory <PropertyModel <TSource, TDestination> >();
            var adapterModelFactory  = FastObjectFactory.CreateObjectFactory <AdapterModel <TSource, TDestination> >();

            var destinationType = typeof(TDestination);
            var sourceType      = typeof(TSource);

            var fields     = new List <FieldModel>();
            var properties = new List <PropertyModel <TSource, TDestination> >();

            var destinationMembers = ReflectionUtils.GetPublicFieldsAndProperties(destinationType);
            var length             = destinationMembers.Length;

            var config    = TypeAdapterConfig <TSource, TDestination> .Configuration;
            var hasConfig = config != null;

            for (var i = 0; i < length; i++)
            {
                var destinationMember = destinationMembers[i];
                var isProperty        = destinationMember is PropertyInfo;

                if (hasConfig)
                {
                    #region Ignore Members

                    var ignoreMembers = config.IgnoreMembers;
                    if (ignoreMembers != null && ignoreMembers.Count > 0)
                    {
                        var ignored = false;
                        for (var j = 0; j < ignoreMembers.Count; j++)
                        {
                            if (destinationMember.Name.Equals(ignoreMembers[j]))
                            {
                                ignored = true;
                                break;
                            }
                        }

                        if (ignored)
                        {
                            continue;
                        }
                    }

                    #endregion

                    #region Custom Resolve

                    var resolvers = config.Resolvers;
                    if (resolvers != null && resolvers.Count > 0)
                    {
                        var hasCustomResolve = false;
                        for (var j = 0; j < resolvers.Count; j++)
                        {
                            var resolver = resolvers[j];
                            if (destinationMember.Name.Equals(resolver.MemberName))
                            {
                                var destinationProperty = (PropertyInfo)destinationMember;

                                var setter = PropertyCaller <TDestination> .CreateSetMethod(destinationProperty);

                                if (setter == null)
                                {
                                    continue;
                                }

                                var propertyModel = (PropertyModel <TSource, TDestination>)propertyModelFactory();
                                propertyModel.ConvertType    = 5;
                                propertyModel.Setter         = setter;
                                propertyModel.CustomResolver = resolver.Invoker;

                                properties.Add(propertyModel);

                                hasCustomResolve = true;
                                break;
                            }
                        }

                        if (hasCustomResolve)
                        {
                            continue;
                        }
                    }

                    #endregion
                }

                var sourceMember =
                    ReflectionUtils.GetPublicFieldOrProperty(sourceType, isProperty, destinationMember.Name);
                if (sourceMember == null)
                {
                    #region Flattening

                    #region GetMethod

                    var getMethod = sourceType.GetMethod(string.Concat("Get", destinationMember.Name));
                    if (getMethod != null)
                    {
                        var setter = PropertyCaller <TDestination> .CreateSetMethod((PropertyInfo)destinationMember);

                        if (setter == null)
                        {
                            continue;
                        }

                        var propertyModel = (PropertyModel <TSource, TDestination>)propertyModelFactory();
                        propertyModel.ConvertType  = 2;
                        propertyModel.Setter       = setter;
                        propertyModel.AdaptInvoker = FastInvoker.GetMethodInvoker(getMethod);

                        properties.Add(propertyModel);

                        continue;
                    }

                    #endregion

                    #region Class

                    var delegates = new List <GenericGetter>();
                    GetDeepFlattening(sourceType, destinationMember.Name, delegates);
                    if (delegates != null && delegates.Count > 0)
                    {
                        var setter = PropertyCaller <TDestination> .CreateSetMethod((PropertyInfo)destinationMember);

                        if (setter == null)
                        {
                            continue;
                        }

                        var propertyModel = (PropertyModel <TSource, TDestination>)propertyModelFactory();
                        propertyModel.ConvertType        = 3;
                        propertyModel.Setter             = setter;
                        propertyModel.FlatteningInvokers = delegates.ToArray();

                        properties.Add(propertyModel);
                    }

                    #endregion

                    #endregion

                    continue;
                }

                if (isProperty)
                {
                    var destinationProperty = (PropertyInfo)destinationMember;

                    var setter = PropertyCaller <TDestination> .CreateSetMethod(destinationProperty);

                    if (setter == null)
                    {
                        continue;
                    }

                    var sourceProperty = (PropertyInfo)sourceMember;

                    var getter = PropertyCaller <TSource> .CreateGetMethod(sourceProperty);

                    if (getter == null)
                    {
                        continue;
                    }

                    var destinationPropertyType = destinationProperty.PropertyType;

                    var propertyModel = (PropertyModel <TSource, TDestination>)propertyModelFactory();
                    propertyModel.Getter = getter;
                    propertyModel.Setter = setter;

                    if (!ReflectionUtils.IsNullable(destinationPropertyType) &&
                        destinationPropertyType != typeof(string) &&
                        ReflectionUtils.IsPrimitive(destinationPropertyType))
                    {
                        propertyModel.DefaultDestinationValue = Activator.CreateInstance(destinationPropertyType);
                    }

                    if (ReflectionUtils.IsPrimitive(destinationPropertyType))
                    {
                        propertyModel.ConvertType = 1;

                        var converter =
                            ReflectionUtils.CreatePrimitiveConverter(sourceProperty.PropertyType,
                                                                     destinationPropertyType);
                        if (converter != null)
                        {
                            propertyModel.AdaptInvoker = converter;
                        }
                    }
                    else
                    {
                        propertyModel.ConvertType = 4;

                        if (ReflectionUtils.IsCollection(destinationPropertyType)) //collections
                        {
                            propertyModel.AdaptInvoker = FastInvoker.GetMethodInvoker(typeof(CollectionAdapter <, ,>)
                                                                                      .MakeGenericType(sourceProperty.PropertyType,
                                                                                                       ReflectionUtils.ExtractElementType(destinationPropertyType),
                                                                                                       destinationPropertyType).GetMethod("Adapt",
                                                                                                                                          new[]
                            {
                                sourceProperty.PropertyType,
                                typeof(Dictionary <,>).MakeGenericType(typeof(int), typeof(int))
                            }));
                        }
                        else // class
                        {
                            if (destinationPropertyType == sourceProperty.PropertyType)
                            {
                                bool newInstance;

                                if (hasConfig && config.NewInstanceForSameType.HasValue)
                                {
                                    newInstance = config.NewInstanceForSameType.Value;
                                }
                                else
                                {
                                    newInstance = TypeAdapterConfig.Configuration.NewInstanceForSameType;
                                }

                                if (!newInstance)
                                {
                                    propertyModel.ConvertType = 1;
                                }
                                else
                                {
                                    propertyModel.AdaptInvoker = FastInvoker.GetMethodInvoker(typeof(ClassAdapter <,>)
                                                                                              .MakeGenericType(sourceProperty.PropertyType, destinationPropertyType)
                                                                                              .GetMethod("Adapt",
                                                                                                         new[]
                                    {
                                        sourceProperty.PropertyType,
                                        typeof(Dictionary <,>).MakeGenericType(typeof(int), typeof(int))
                                    }));
                                }
                            }
                            else
                            {
                                propertyModel.AdaptInvoker = FastInvoker.GetMethodInvoker(typeof(ClassAdapter <,>)
                                                                                          .MakeGenericType(sourceProperty.PropertyType, destinationPropertyType)
                                                                                          .GetMethod("Adapt",
                                                                                                     new[]
                                {
                                    sourceProperty.PropertyType,
                                    typeof(Dictionary <,>).MakeGenericType(typeof(int), typeof(int))
                                }));
                            }
                        }
                    }

                    properties.Add(propertyModel);
                }
                else // Fields
                {
                    var fieldModel    = (FieldModel)fieldModelFactory();
                    var fieldInfoType = typeof(FieldInfo);

                    fieldModel.Getter = FastInvoker.GetMethodInvoker(fieldInfoType.GetMethod("GetValue"));
                    fieldModel.Setter = FastInvoker.GetMethodInvoker(fieldInfoType.GetMethod("SetValue"));

                    fields.Add(fieldModel);
                }
            }

            var adapterModel = (AdapterModel <TSource, TDestination>)adapterModelFactory();
            adapterModel.Fields     = fields.ToArray();
            adapterModel.Properties = properties.ToArray();

            return(adapterModel);
        }
 static bool Prepare()
 {
     IsSpendRulerTimeDays = Accessors.CreateInvoker <KingdomUIEventWindowFooter, bool>("IsSpendRulerTimeDays");
     return(true);
 }
Beispiel #16
0
        public void Invoke <TMessage>(ConsumerDescriptor descriptor, IConsumer consumer, ConsumeContext <TMessage> envelope) where TMessage : class
        {
            var d           = descriptor;
            var p           = descriptor.WithEnvelope ? (object)envelope : envelope.Message;
            var fastInvoker = FastInvoker.GetInvoker(d.Method);

            var items = HttpContext.Current.GetItem("ConsumerInvoker", () => new List <ConsumerDescriptor>());

            items.Add(d);

            if (!d.FireForget && !d.IsAsync)
            {
                // The all synch case
                try
                {
                    InvokeCore();
                }
                catch (Exception ex)
                {
                    HandleException(ex, d);
                }
            }
            else if (!d.FireForget && d.IsAsync)
            {
                // The awaitable Task case
                BeginInvoke((Task)InvokeCore(cancelToken: AsyncRunner.AppShutdownCancellationToken), EndInvoke, d);
            }
            else if (d.FireForget && !d.IsAsync)
            {
                // A synch method should be executed async (without awaiting)
                AsyncRunner.Run((c, ct, state) => InvokeCore(c, ct), d)
                .ContinueWith(t => EndInvoke(t), /*TaskContinuationOptions.OnlyOnFaulted*/ TaskContinuationOptions.None)
                .ConfigureAwait(false);
            }
            else if (d.FireForget && d.IsAsync)
            {
                // An async (Task) method should be executed without awaiting
                AsyncRunner.Run((c, ct) => (Task)InvokeCore(c, ct), d)
                .ContinueWith(t => EndInvoke(t), TaskContinuationOptions.OnlyOnFaulted)
                .ConfigureAwait(false);
            }

            object InvokeCore(IComponentContext c = null, CancellationToken cancelToken = default(CancellationToken))
            {
                if (d.Parameters.Length == 0)
                {
                    // Only one method param: the message!
                    return(fastInvoker.Invoke(consumer, p));
                }

                var parameters = new object[d.Parameters.Length + 1];

                parameters[0] = p;

                int i = 0;

                foreach (var obj in ResolveParameters(c, d, cancelToken).ToArray())
                {
                    i++;
                    parameters[i] = obj;
                }

                return(fastInvoker.Invoke(consumer, parameters));
            }
        }
Beispiel #17
0
        private static AdapterModel <TSource, TDestination> CreateAdapterModel()
        {
            Func <FieldModel> fieldModelFactory = FastObjectFactory.CreateObjectFactory <FieldModel>();
            Func <PropertyModel <TSource, TDestination> > propertyModelFactory = FastObjectFactory.CreateObjectFactory <PropertyModel <TSource, TDestination> >();
            Func <AdapterModel <TSource, TDestination> >  adapterModelFactory  = FastObjectFactory.CreateObjectFactory <AdapterModel <TSource, TDestination> >();

            Type destinationType = typeof(TDestination);
            Type sourceType      = typeof(TSource);

            var unmappedDestinationMembers = new List <string>();

            var fields     = new List <FieldModel>();
            var properties = new List <PropertyModel <TSource, TDestination> >();

            List <MemberInfo> destinationMembers = destinationType.GetPublicFieldsAndProperties(allowNoSetter: false);

            var configSettings = TypeAdapterConfig <TSource, TDestination> .ConfigSettings;

            bool hasConfig = configSettings != null;

            if (!hasConfig && TypeAdapterConfig.GlobalSettings.RequireExplicitMapping && sourceType != destinationType)
            {
                throw new InvalidOperationException(
                          String.Format("Implicit mapping is not allowed (check GlobalSettings.AllowImplicitMapping) and no configuration exists for the following mapping: TSource: {0} TDestination: {1}",
                                        typeof(TSource), typeof(TDestination)));
            }

            IDictionary <Type, Func <object, object> > destinationTransforms = hasConfig
                ? configSettings.DestinationTransforms.Transforms : TypeAdapterConfig.GlobalSettings.DestinationTransforms.Transforms;

            for (int i = 0; i < destinationMembers.Count; i++)
            {
                MemberInfo destinationMember = destinationMembers[i];
                bool       isProperty        = destinationMember is PropertyInfo;

                if (hasConfig)
                {
                    if (ProcessIgnores(configSettings, destinationMember))
                    {
                        continue;
                    }

                    if (ProcessCustomResolvers(configSettings, destinationMember, propertyModelFactory, properties, destinationTransforms))
                    {
                        continue;
                    }
                }

                MemberInfo sourceMember = ReflectionUtils.GetPublicFieldOrProperty(sourceType, isProperty, destinationMember.Name);
                if (sourceMember == null)
                {
                    if (FlattenMethod(sourceType, destinationMember, propertyModelFactory, properties, destinationTransforms))
                    {
                        continue;
                    }

                    if (FlattenClass(sourceType, destinationMember, propertyModelFactory, properties, destinationTransforms))
                    {
                        continue;
                    }

                    if (destinationMember.HasPublicSetter())
                    {
                        unmappedDestinationMembers.Add(destinationMember.Name);
                    }

                    continue;
                }

                if (isProperty)
                {
                    var destinationProperty = (PropertyInfo)destinationMember;

                    var setter = PropertyCaller <TDestination> .CreateSetMethod(destinationProperty);

                    if (setter == null)
                    {
                        continue;
                    }

                    var sourceProperty = (PropertyInfo)sourceMember;

                    var getter = PropertyCaller <TSource> .CreateGetMethod(sourceProperty);

                    if (getter == null)
                    {
                        continue;
                    }

                    Type destinationPropertyType = destinationProperty.PropertyType;

                    var propertyModel = propertyModelFactory();
                    propertyModel.Getter             = getter;
                    propertyModel.Setter             = setter;
                    propertyModel.SetterPropertyName = ExtractPropertyName(setter, "Set");
                    if (destinationTransforms.ContainsKey(destinationPropertyType))
                    {
                        propertyModel.DestinationTransform = destinationTransforms[destinationPropertyType];
                    }

                    //if (!ReflectionUtils.IsNullable(destinationPropertyType) && destinationPropertyType != typeof(string) && ReflectionUtils.IsPrimitive(destinationPropertyType))
                    //    propertyModel.DefaultDestinationValue = new TDestination();

                    if (destinationPropertyType.IsPrimitiveRoot())
                    {
                        propertyModel.ConvertType = 1;

                        var converter = sourceProperty.PropertyType.CreatePrimitiveConverter(destinationPropertyType);
                        if (converter != null)
                        {
                            propertyModel.AdaptInvoker = converter;
                        }
                    }
                    else
                    {
                        propertyModel.ConvertType = 4;

                        if (destinationPropertyType.IsCollection()) //collections
                        {
                            propertyModel.AdaptInvoker =
                                FastInvoker.GetMethodInvoker(
                                    typeof(CollectionAdapter <, , ,>).MakeGenericType(
                                        sourceProperty.PropertyType.ExtractCollectionType(), sourceProperty.PropertyType,
                                        destinationPropertyType.ExtractCollectionType(), destinationPropertyType)
                                    .GetMethod("Adapt",
                                               new[]
                            {
                                sourceProperty.PropertyType,
                                typeof(bool),
                                typeof(Dictionary <,>).MakeGenericType(typeof(long), typeof(int))
                            }));
                        }
                        else // class
                        {
                            if (destinationPropertyType == sourceProperty.PropertyType)
                            {
                                bool newInstance;

                                if (hasConfig && configSettings.NewInstanceForSameType.HasValue)
                                {
                                    newInstance = configSettings.NewInstanceForSameType.Value;
                                }
                                else
                                {
                                    newInstance = TypeAdapterConfig.ConfigSettings.NewInstanceForSameType;
                                }

                                if (!newInstance)
                                {
                                    propertyModel.ConvertType = 1;
                                }
                                else
                                {
                                    propertyModel.AdaptInvoker =
                                        FastInvoker.GetMethodInvoker(typeof(ClassAdapter <,>)
                                                                     .MakeGenericType(sourceProperty.PropertyType, destinationPropertyType)
                                                                     .GetMethod("Adapt",
                                                                                new[]
                                    {
                                        sourceProperty.PropertyType,
                                        typeof(bool),
                                        typeof(Dictionary <,>).MakeGenericType(typeof(long), typeof(int))
                                    }));
                                }
                            }
                            else
                            {
                                propertyModel.AdaptInvoker = FastInvoker.GetMethodInvoker(typeof(ClassAdapter <,>)
                                                                                          .MakeGenericType(sourceProperty.PropertyType, destinationPropertyType)
                                                                                          .GetMethod("Adapt",
                                                                                                     new[]
                                {
                                    sourceProperty.PropertyType,
                                    typeof(bool),
                                    typeof(Dictionary <,>).MakeGenericType(typeof(long), typeof(int))
                                }));
                            }
                        }
                    }

                    properties.Add(propertyModel);
                }
                else // Fields
                {
                    var fieldModel    = fieldModelFactory();
                    var fieldInfoType = typeof(FieldInfo);

                    fieldModel.Getter = FastInvoker.GetMethodInvoker(fieldInfoType.GetMethod("GetValue"));
                    fieldModel.Setter = FastInvoker.GetMethodInvoker(fieldInfoType.GetMethod("SetValue"));

                    fields.Add(fieldModel);
                }
            }

            if (TypeAdapterConfig.GlobalSettings.RequireDestinationMemberSource && unmappedDestinationMembers.Count > 0)
            {
                throw new ArgumentOutOfRangeException(String.Format("The following members of destination class {0} do not have a corresponding source member mapped or ignored:{1}",
                                                                    typeof(TDestination), String.Join(",", unmappedDestinationMembers)));
            }

            var adapterModel = adapterModelFactory();

            adapterModel.Fields     = fields.ToArray();
            adapterModel.Properties = properties.ToArray();

            return(adapterModel);
        }
Beispiel #18
0
 static bool Prepare()
 {
     UnscaleFxTimes = Accessors.CreateInvoker <DollRoom, GameObject, object>("UnscaleFxTimes");
     return(true);
 }