This project is read-only.
1
Vote

Found fix for clone injection for latest version

description

I previously mention in my previous issue that clone injection works for 2.3.3 but not for the latest version. Please find my fix below:

private static object GetClone(PropertyInfo sp, PropertyInfo tp, object val)
    {
        if (sp.PropertyType.IsValueType || sp.PropertyType == typeof(string))
        {
            return val;
        }

        if (sp.PropertyType.IsArray)
        {
            var arr = val as Array;
            var arrClone = arr.Clone() as Array;

            for (int index = 0; index < arr.Length; index++)
            {
                var a = arr.GetValue(index);
                if (a.GetType().IsValueType || a is string) continue;

                arrClone.SetValue(Activator.CreateInstance(a.GetType()).InjectFrom<CloneInjection>(a), index);
            }

            return arrClone;
        }

        if (sp.PropertyType.IsGenericType)
        {
            //handle IEnumerable<> also ICollection<> IList<> List<>
            if (sp.PropertyType.GetGenericTypeDefinition().GetInterfaces().Contains(typeof(IEnumerable)))
            {
                var genericType = sp.PropertyType.GetGenericArguments()[0];

                // Added by JT: Fix for deep cloning
                if (sp.PropertyType.IsValueType || sp.PropertyType == typeof(string))
                {
                    return val;
                }

                // Added by JT: Fix for deep cloning
                genericType = tp.PropertyType.GetGenericArguments()[0];

                var listType = typeof(List<>).MakeGenericType(genericType);
                var list = Activator.CreateInstance(listType);

                var addMethod = listType.GetMethod("Add");
                foreach (var o in val as IEnumerable)
                {
                    var listItem = genericType.IsValueType || genericType == typeof(string) ? o : Activator.CreateInstance(genericType).InjectFrom<CloneInjection>(o);
                    addMethod.Invoke(list, new[] { listItem });
                }

                return list;
            }

            //unhandled generic type, you could also return null or throw
            return val;
        }

        //for simple object types create a new instance and apply the clone injection on it
        return Activator.CreateInstance(sp.PropertyType)
                        .InjectFrom<CloneInjection>(val);
    }

comments