예제 #1
0
 private T method_19 <T>(IntPtr intptr_1) where T : class
 {
     if (intptr_1 == IntPtr.Zero)
     {
         return(default(T));
     }
     return(FastObjectFactory.CreateObjectInstance <T>(intptr_1));
 }
예제 #2
0
        internal T method_3 <T>(string string_4) where T : class
        {
            IntPtr ptr = this.method_5(string_4);

            if (ptr == IntPtr.Zero)
            {
                return(default(T));
            }
            return(FastObjectFactory.CreateObjectInstance <T>(ptr));
        }
예제 #3
0
        internal static T smethod_16 <T>(string string_4, string string_5, string string_6, string string_7, Class272.Enum20[] enum20_0, params object[] object_0) where T : MonoClass
        {
            IntPtr ptr = smethod_10(string_4, string_5, string_6, string_7, enum20_0, object_0);

            if (ptr == IntPtr.Zero)
            {
                return(default(T));
            }
            return(FastObjectFactory.CreateObjectInstance <T>(ptr));
        }
예제 #4
0
        internal static T smethod_7 <T>(string string_4, string string_5, string string_6, string string_7) where T : class
        {
            IntPtr ptr = smethod_9(string_4, string_5, string_6, string_7);

            if (ptr == IntPtr.Zero)
            {
                return(default(T));
            }
            return(FastObjectFactory.CreateObjectInstance <T>(ptr));
        }
예제 #5
0
        private T InvokeMethodByRetClass <T>(string methodName) where T : class
        {
            IntPtr intPtr = MonoClassInternalMethod5(methodName);

            if (intPtr == IntPtr.Zero)
            {
                return(default(T));
            }

            return(FastObjectFactory.CreateObjectInstance <T>(intPtr));
        }
예제 #6
0
        public SimpleMedalInfoTranslator GetLocalPlayerMedalInfo()
        {
            MethodInfo method7 = this.GetType().GetMethod("method_7", BindingFlags.Instance | BindingFlags.NonPublic);
            IntPtr     intPtr  = (IntPtr)method7.Invoke(this,
                                                        new object[] { "GetLocalPlayerMedalInfo", null, Array.Empty <object>() });

            if (intPtr == IntPtr.Zero)
            {
                return(default(SimpleMedalInfoTranslator));
            }

            return(FastObjectFactory.CreateObjectInstance <SimpleMedalInfoTranslator>(intPtr));
        }
예제 #7
0
        public SimplTranslatedMedalInfo GetCurrentMedal(bool useWildMedal)
        {
            MethodInfo method7 = this.GetType().GetMethod("method_7", BindingFlags.Instance | BindingFlags.NonPublic);
            IntPtr     intPtr  = (IntPtr)method7.Invoke(this,
                                                        new object[] { "GetCurrentMedal", null, new object[] { useWildMedal } });

            if (intPtr == IntPtr.Zero)
            {
                return(default(SimplTranslatedMedalInfo));
            }

            return(FastObjectFactory.CreateObjectInstance <SimplTranslatedMedalInfo>(intPtr));
        }
예제 #8
0
        internal T method_15 <T>(string string_4, Class272.Enum20[] enum20_0, params object[] object_0) where T : class
        {
            if (!typeof(T).IsClass)
            {
                object[] objArray1 = new object[] { typeof(T), " is not a class type. Please fix the method invocation for ", this.ClassName, ".", string_4, " to use Get<T> or GetString instead." };
                throw new InvalidOperationException(string.Concat(objArray1));
            }
            IntPtr ptr = this.method_7(string_4, enum20_0, object_0);

            if (ptr == IntPtr.Zero)
            {
                return(default(T));
            }
            return(FastObjectFactory.CreateObjectInstance <T>(ptr));
        }
            IEnumerable <FastObjectFactory.CreateObject> GetCreateControllerDelegates()
            {
                var controllerActivationPolicy = _modelListViewPreviewRowDetailView.PreviewRowControllers.ControllerActivationPolicy;

                if (controllerActivationPolicy == ControllerActivationPolicy.Default)
                {
                    return(null);
                }
                if (controllerActivationPolicy == ControllerActivationPolicy.DoNotActivate)
                {
                    return(Enumerable.Empty <FastObjectFactory.CreateObject>());
                }
                var modelPreviewRowControllers = _modelListViewPreviewRowDetailView.PreviewRowControllers.Where(controller => controller.Activate);

                return(modelPreviewRowControllers.Select(controller => FastObjectFactory.CreateObjectFactory(Type.GetType(controller.Name))));
            }
예제 #10
0
        /// <summary>
        /// Raises the <see cref="DataParsed"/> event.
        /// </summary>
        /// <param name="output">The object that was deserialized from binary image.</param>
        protected virtual void OnDataParsed(TOutputType output)
        {
            if ((object)DataParsed != null)
            {
                // Get a reusable event args object to publish output
                EventArgs <TOutputType> outputArgs = FastObjectFactory <EventArgs <TOutputType> > .CreateObjectFunction();

                outputArgs.Argument = output;

                if (output.AllowQueuedPublication)
                {
                    // Queue-up parsed output for publication
                    m_outputQueue.Enqueue(outputArgs);
                }
                else
                {
                    // Publish parsed output immediately
                    DataParsed(this, outputArgs);
                }
            }
        }
예제 #11
0
        /// <summary>
        /// Queues a sequence of bytes, from the specified data source, onto the stream for parsing.
        /// </summary>
        /// <param name="source">Identifier of the data source.</param>
        /// <param name="buffer">An array of bytes. This method copies count bytes from buffer to the queue.</param>
        /// <param name="offset">The zero-based byte offset in buffer at which to begin copying bytes to the current stream.</param>
        /// <param name="count">The number of bytes to be written to the current stream.</param>
        /// <remarks>
        /// This method associates a buffer with its data source identifier.
        /// </remarks>
        public virtual void Parse(TSourceIdentifier source, byte[] buffer, int offset, int count)
        {
            SourceIdentifiableBuffer identifiableBuffer = null;

            buffer.ValidateParameters(offset, count);

            if (count > 0)
            {
                // Get an identifiable buffer object
                identifiableBuffer = FastObjectFactory <SourceIdentifiableBuffer> .CreateObjectFunction();

                identifiableBuffer.Source = source;
                identifiableBuffer.Count  = count;

                // Copy buffer data for processing
                Buffer.BlockCopy(buffer, offset, identifiableBuffer.Buffer, 0, count);

                // Add buffer to the queue for parsing. Note that buffer is queued for parsing instead
                // of handling parse on this thread - this has become necessary to reduce UDP data loss
                // that can happen in-process when system has UDP buffers building up for processing.
                m_bufferQueue.Enqueue(new[] { identifiableBuffer });
            }
        }
예제 #12
0
        /// <summary>
        /// Queues a sequence of bytes, from the specified data source, onto the stream for parsing.
        /// </summary>
        /// <param name="source">Identifier of the data source.</param>
        /// <param name="buffer">An array of bytes. This method copies count bytes from buffer to the queue.</param>
        /// <param name="offset">The zero-based byte offset in buffer at which to begin copying bytes to the current stream.</param>
        /// <param name="count">The number of bytes to be written to the current stream.</param>
        /// <remarks>
        /// This method associates a buffer with its data source identifier.
        /// </remarks>
        public virtual void Parse(TSourceIdentifier source, byte[] buffer, int offset, int count)
        {
            SourceIdentifiableBuffer identifiableBuffer = null;

            buffer.ValidateParameters(offset, count);

            if (count > 0)
            {
                // Get an identifiable buffer object
                identifiableBuffer = FastObjectFactory <SourceIdentifiableBuffer> .CreateObjectFunction();

                identifiableBuffer.Source = source;
                identifiableBuffer.Count  = count;

                // Copy buffer data for processing
                Buffer.BlockCopy(buffer, offset, identifiableBuffer.Buffer, 0, count);

                // Add buffer to the queue for parsing. Note that buffer is queued for parsing instead
                // of handling parse on this thread - this has become necessary to reduce UDP data loss
                // that can happen in-process when system has UDP buffers building up for processing.
                if (OptimizationOptions.DisableAsyncQueueInProtocolParsing)
                {
                    try
                    {
                        ParseQueuedBuffers(new[] { identifiableBuffer });
                    }
                    catch (Exception ex)
                    {
                        ProcessExceptionHandler(this, new EventArgs <Exception>(ex));
                    }
                }
                else
                {
                    m_bufferQueue.Enqueue(new[] { identifiableBuffer });
                }
            }
        }
예제 #13
0
        /// <summary>
        ///     Content list is a simpler 'BetterList' version without ability to move objects and is designed to draw all items at once.
        /// </summary>
        public static List <T1> ContentList <T1, T2>([NotNull] List <T1> list, [NotNull] T2 target, JEMBetterEditorEvents <T1> @event, JEMBetterEditorStyle style)
        {
            if (list == null)
            {
                throw new ArgumentNullException(nameof(list));
            }
            if (target == null)
            {
                throw new ArgumentNullException(nameof(target));
            }

            if (@event.OnDraw == null)
            {
                EditorGUILayout.HelpBox("BetterList error. Events OnDraw must be set.", MessageType.Error);
                return(list);
            }

            DrawBetterEditorGroup(style, () =>
            {
                var prevEnable = GUI.enabled;
                if (style.Readonly)
                {
                    GUI.enabled = false;
                }

                for (var index = 0; index < list.Count; index++)
                {
                    EditorGUILayout.BeginHorizontal("box");
                    {
                        list[index] = @event.OnDraw(list[index]);
                        GUILayout.FlexibleSpace();
                        GUI.color = Color.red;
                        if (GUILayout.Button("Remove", GUILayout.Width(70)))
                        {
                            if (@event.OnRemove != null)
                            {
                                @event.OnRemove(list[index]);
                            }
                            else
                            {
                                list.RemoveAt(index);
                            }

                            index--;
                        }

                        GUI.color = Color.white;
                    }
                    EditorGUILayout.EndHorizontal();
                }

                EditorGUILayout.BeginHorizontal("box");
                {
                    GUILayout.FlexibleSpace();
                    GUI.color = Color.green;
                    if (GUILayout.Button("New", GUILayout.Width(70)))
                    {
                        if (@event.OnAdd != null)
                        {
                            @event.OnAdd.Invoke();
                        }
                        else
                        {
                            var newInstance = FastObjectFactory <T1> .Instance();
                            list.Add(newInstance);
                        }
                    }

                    GUI.color = Color.white;
                }
                EditorGUILayout.EndHorizontal();

                GUI.enabled = prevEnable;
            }, @event.OnDrawMenu);

            return(list);
        }
예제 #14
0
        /// <summary>
        ///     Better list is replace for unity's array/list property control.
        ///     Implements custom item editor and adds ability to move items in list.
        /// </summary>
        public static List <T1> BetterList <T1, T2>([NotNull] List <T1> list, [NotNull] T2 target, ref Vector2 scroll, JEMBetterEditorEvents <T1> @event, JEMBetterEditorStyle style) where T2 : Object
        {
            if (list == null)
            {
                throw new ArgumentNullException(nameof(list));
            }
            if (target == null)
            {
                throw new ArgumentNullException(nameof(target));
            }
            if (@event.OnDraw == null)
            {
                EditorGUILayout.HelpBox("BetterList error. Events OnDraw must be set.", MessageType.Error);
                return(list);
            }

            var targetName = $"{style.EditorName}.{typeof(T1)}";
            var scroll1    = scroll;

            DrawBetterEditorGroup(style, () =>
            {
                var newList = list;
                EditorGUI.BeginChangeCheck();
                scroll1 = EditorGUILayout.BeginScrollView(scroll1);
                {
                    for (var index = 0; index < newList.Count; index++)
                    {
                        BeginFixedIndent();
                        {
                            EditorGUILayout.BeginVertical();
                            {
                                var itemName    = $"{targetName}.Item.{index}";
                                var headerIndex = style.ItemFixedIndex ? index + 1 : index;
                                var headerText  = $"{style.ItemPrefix} #{headerIndex}";
                                @event.OnPreDraw?.Invoke(newList[index]);

                                EditorGUILayout.BeginHorizontal();
                                bool shouldShow = EditorPrefs.GetBool(itemName);
                                bool show       = EditorGUILayout.Foldout(shouldShow, headerText);
                                var showMenu    = GUILayout.Button(string.Empty, EditorStyles.foldoutHeaderIcon,
                                                                   GUILayout.Width(15));
                                if (showMenu)
                                {
                                    var menu = new GenericMenu();
                                    if (index - 1 >= 0)
                                    {
                                        var index1 = index;
                                        menu.AddItem(new GUIContent("Move up"), false, () =>
                                        {
                                            var obj = newList[index1];
                                            newList.RemoveAt(index1);
                                            newList.Insert(index1 - 1, obj);
                                            GUI.FocusControl(null);
                                        });
                                    }

                                    if (index + 1 < newList.Count)
                                    {
                                        var index1 = index;
                                        menu.AddItem(new GUIContent("Move down"), false, () =>
                                        {
                                            var obj = newList[index1];
                                            newList.RemoveAt(index1);
                                            newList.Insert(index1 + 1, obj);
                                            GUI.FocusControl(null);
                                        });
                                    }

                                    var index2 = index;
                                    menu.AddItem(new GUIContent("Remove"), false, () =>
                                    {
                                        var @continue = true;
                                        if (Event.current == null || Event.current.keyCode != KeyCode.LeftControl)
                                        {
                                            if (!EditorUtility.DisplayDialog("Continue?",
                                                                             $"Do you really want to delete {style.ItemPrefix} #{index2}?", "Yes",
                                                                             "No"))
                                            {
                                                @continue = false;
                                            }
                                        }

                                        if (@continue)
                                        {
                                            if (@event.OnRemove != null)
                                            {
                                                @event.OnRemove.Invoke(newList[index2]);
                                            }
                                            else
                                            {
                                                newList.RemoveAt(index2);
                                            }

                                            index--;
                                            GUI.FocusControl(null);
                                        }
                                    });
                                    menu.ShowAsContext();
                                }
                                EditorGUILayout.EndHorizontal();

                                if (show)
                                {
                                    BeginFixedIndent();
                                    {
                                        EditorGUILayout.BeginVertical();
                                        newList[index] = @event.OnDraw.Invoke(newList[index]);
                                        EditorGUILayout.Space();
                                        EditorGUILayout.EndVertical();
                                    }
                                    EndFixedIndent();
                                }

                                if (show != shouldShow)
                                {
                                    EditorPrefs.SetBool(itemName, show);
                                }
                                @event.OnPostDraw?.Invoke(newList[index]);
                            }
                            EditorGUILayout.EndVertical();
                        }
                        EndFixedIndent();
                    }

                    BeginFixedIndent(2, true);
                    EditorGUILayout.BeginHorizontal(GUILayout.Height(14));
                    {
                        // GUILayout.FlexibleSpace();
                        GUI.color = Color.green;
                        if (GUILayout.Button($"Add new {style.DrawName}", EditorStyles.miniButton, GUILayout.Height(14)))
                        {
                            GUI.FocusControl(null);
                            if (@event.OnAdd != null)
                            {
                                @event.OnAdd.Invoke();
                            }
                            else
                            {
                                var itemName = $"{targetName}.Item.{newList.Count}";
                                EditorPrefs.SetBool(itemName, true);
                                var newInstance = FastObjectFactory <T1> .Instance();
                                newList.Add(newInstance);
                            }
                        }
                        GUILayout.FlexibleSpace();
                        GUI.color = Color.white;
                    }
                    EditorGUILayout.EndHorizontal();
                    EndFixedIndent(2);
                }
                EditorGUILayout.EndScrollView();
                if (EditorGUI.EndChangeCheck())
                {
                    Undo.RegisterCompleteObjectUndo(target, $"{targetName}.Change");
                    list = newList;
                }
            }, @event.OnDrawMenu);
            scroll = scroll1;
            return(list);
        }
예제 #15
0
        /// <summary>
        /// Starts the data parser given the specified type implementations.
        /// </summary>
        /// <param name="implementations">Output type implementations to establish for the parser.</param>
        public virtual void Start(IEnumerable <Type> implementations)
        {
            // Call base class start method
            base.Start();

            ConstructorInfo typeCtor;
            List <TypeInfo> outputTypes = new List <TypeInfo>();  // Temporarily hold output types until their IDs are determined.

            foreach (Type type in implementations)
            {
                // See if a parameterless constructor is available for this type
                typeCtor = type.GetConstructor(Type.EmptyTypes);

                // Since user can call this overload with any list of types, we double check the type criteria.
                // If output type is a class, see if current type derives from it, else if output type is an
                // interface, see if current type implements it.
                if ((object)typeCtor != null && !type.IsAbstract &&
                    (
                        (typeof(TOutputType).IsClass && type.IsSubclassOf(typeof(TOutputType))) ||
                        (typeof(TOutputType).IsInterface && (object)type.GetInterface(typeof(TOutputType).Name) != null))
                    )
                {
                    // The type meets the following criteria:
                    //      - has a default public constructor
                    //      - is not abstract and can be instantiated.
                    //      - type is related to class or interface specified for the output
                    TypeInfo outputType = new TypeInfo
                    {
                        RuntimeType = type
                    };

                    // If class implementation supports life cycle, automatically dispose of objects when we are done with them
                    outputType.SupportsLifecycle = (object)type.GetInterface("GSF.ISupportLifecycle") != null;
                    outputType.CreateNew         = FastObjectFactory.GetCreateObjectFunction <TOutputType>(type);

                    // We'll hold all of the matching types in this list temporarily until their IDs are determined.
                    outputTypes.Add(outputType);
                }
            }

            foreach (TypeInfo outputType in outputTypes)
            {
                // Now, we'll go though all of the output types we've found and instantiate an instance of each in order to get
                // the identifier for each of the type. This will help lookup of the type to be used when parsing the data.
                TOutputType instance = outputType.CreateNew();
                outputType.TypeID = instance.TypeID;

                if (!m_outputTypes.ContainsKey(outputType.TypeID))
                {
                    m_outputTypes.Add(outputType.TypeID, outputType);
                }
                else
                {
                    OnDuplicateTypeHandlerEncountered(outputType.RuntimeType, outputType.TypeID);
                }

                // Dispose of the object if it supports lifecycle management
                if (outputType.SupportsLifecycle)
                {
                    ((IDisposable)instance).Dispose();
                }
            }
        }
예제 #16
0
        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);
        }
예제 #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);
        }