System.Reflection.FieldInfo.SetValue(object, object)

Here are the examples of the csharp api System.Reflection.FieldInfo.SetValue(object, object) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1722 Examples 7

19 View Source File : CelesteNetClientModule.cs
License : MIT License
Project Creator : 0x0ade

protected override void CreateModMenuSectionHeader(TextMenu menu, bool inGame, EventInstance snapshot) {
            base.CreateModMenuSectionHeader(menu, inGame, snapshot);

            CelesteNetModShareComponent sharer = Context?.Get<CelesteNetModShareComponent>();
            if (sharer != null && !inGame) {
                List<EverestModuleMetadata> requested;
                lock (sharer.Requested)
                    requested = new List<EverestModuleMetadata>(sharer.Requested);

                if (requested.Count != 0) {
                    TextMenu.Item item;
                    menu.Add(item = new TextMenu.Button("modoptions_celestenetclient_recommended".DialogClean()).Pressed(() => {
                        f_OuiDependencyDownloader_MissingDependencies.SetValue(null, requested);
                        m_Overworld_Goto_OuiDependencyDownloader.Invoke(Engine.Scene, Dummy<object>.EmptyArray);
                    }));

                    item.AddDescription(
                        menu,
                        "modoptions_celestenetclient_recommendedhint".DialogClean()
                        .Replace("((list))", string.Join(", ", requested.Select(r => r.DLL)))
                    );
                }
            }
        }

19 View Source File : CelesteNetClientUtils.cs
License : MIT License
Project Creator : 0x0ade

public static int AddState(this StateMachine machine, Func<int> onUpdate, Func<IEnumerator> coroutine = null, Action begin = null, Action end = null) {
            Action[] begins = (Action[]) f_StateMachine_begins.GetValue(machine);
            Func<int>[] updates = (Func<int>[]) f_StateMachine_updates.GetValue(machine);
            Action[] ends = (Action[]) f_StateMachine_ends.GetValue(machine);
            Func<IEnumerator>[] coroutines = (Func<IEnumerator>[]) f_StateMachine_coroutines.GetValue(machine);
            int nextIndex = begins.Length;
            Array.Resize(ref begins, begins.Length + 1);
            Array.Resize(ref updates, begins.Length + 1);
            Array.Resize(ref ends, begins.Length + 1);
            Array.Resize(ref coroutines, coroutines.Length + 1);
            f_StateMachine_begins.SetValue(machine, begins);
            f_StateMachine_updates.SetValue(machine, updates);
            f_StateMachine_ends.SetValue(machine, ends);
            f_StateMachine_coroutines.SetValue(machine, coroutines);
            machine.SetCallbacks(nextIndex, onUpdate, coroutine, begin, end);
            return nextIndex;
        }

19 View Source File : XnaToFnaHelper.cs
License : zlib License
Project Creator : 0x0ade

public static void PlatformHook(string name) {
            Type t_Helper = typeof(XnaToFnaHelper);

            replacedembly fna = replacedembly.Getreplacedembly(typeof(Game));
            FieldInfo field = fna.GetType("Microsoft.Xna.Framework.FNAPlatform").GetField(name);

            // Store the original delegate into fna_name.
            t_Helper.GetField($"fna_{name}").SetValue(null, field.GetValue(null));
            // Replace the value with the new method.
            field.SetValue(null, Delegate.CreateDelegate(fna.GetType($"Microsoft.Xna.Framework.FNAPlatform+{name}Func"), t_Helper.GetMethod(name)));
        }

19 View Source File : RandomHelper.cs
License : MIT License
Project Creator : 1996v

public static object RandomValue(this Type t, bool stringValueAllowEmpty = true)
        {
            if (t.IsPrimitive)
            {
                if (t == typeof(byte))
                {
                    return (byte)(Rand.Next(byte.MaxValue - byte.MinValue + 1) + byte.MinValue);
                }

                if (t == typeof(sbyte))
                {
                    return (sbyte)(Rand.Next(sbyte.MaxValue - sbyte.MinValue + 1) + sbyte.MinValue);
                }

                if (t == typeof(short))
                {
                    return (short)(Rand.Next(short.MaxValue - short.MinValue + 1) + short.MinValue);
                }

                if (t == typeof(ushort))
                {
                    return (ushort)(Rand.Next(ushort.MaxValue - ushort.MinValue + 1) + ushort.MinValue);
                }

                if (t == typeof(int))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToInt32(bytes, 0);
                }

                if (t == typeof(uint))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToUInt32(bytes, 0);
                }

                if (t == typeof(long))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToInt64(bytes, 0);
                }

                if (t == typeof(ulong))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToUInt64(bytes, 0);
                }

                if (t == typeof(float))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    var f = BitConverter.ToSingle(bytes, 0);
                    if (float.IsNaN(f))
                        f = (float)RandomValue<short>();
                    return f;
                }

                if (t == typeof(double))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    var d= BitConverter.ToDouble(bytes, 0);
                    if (double.IsNaN(d))
                        d = (double)RandomValue<short>();
                    return d;
                }

                if (t == typeof(char))
                {
                    var roll = Rand.Next(ASCII.Length);

                    return ASCII[roll];
                }

                if (t == typeof(bool))
                {
                    return (Rand.Next(2) == 1);
                }

                throw new InvalidOperationException();
            }

            if (t == typeof(decimal))
            {
                return new decimal((int)typeof(int).RandomValue(), (int)typeof(int).RandomValue(), (int)typeof(int).RandomValue(), false, 28);
            }

            if (t == typeof(string))
            {
                int start = stringValueAllowEmpty ? 0 : 1;
                var len = Rand.Next(start, 40);
                var c = new char[len];
                for (var i = 0; i < c.Length; i++)
                {
                    c[i] = (char)typeof(char).RandomValue();
                }

                return new string(c);
            }

            if (t == typeof(DateTime))
            {
                var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

                var bytes = new byte[4];
                Rand.NextBytes(bytes);

                var secsOffset = BitConverter.ToInt32(bytes, 0);

                var retDate = epoch.AddSeconds(secsOffset);

                return retDate;
            }

            if (t == typeof(TimeSpan))
            {
                return new TimeSpan(RandomValue<DateTime>().Ticks);
            }

            if (t == typeof(DataTable))
            {
                DataTable dt = new DataTable();
                int coluCount = Rand.Next(10, 30);
                for (int i = 0; i < coluCount; i++)
                {
                    string n = RandomHelper.RandomValue<string>(false);
                    while(dt.Columns.Contains(n))
                        n = RandomHelper.RandomValue<string>(false);
                    dt.Columns.Add(n, typeof(object));
                }
                int rowCount = Rand.Next(20, 50);
                for (int i = 0; i < rowCount; i++)
                {
                    var row = new object[coluCount];
                    for (int zi = 0; zi < coluCount; zi++)
                    {
                        row[zi] = RandomHelper.RandomValue<object>();
                    }
                    dt.Rows.Add(row);
                }
                return dt;
            }

            if (t.IsNullable())
            {
                // leave it unset
                if (Rand.Next(2) == 0)
                {
                    // null!
                    return Activator.CreateInstance(t);
                }

                var underlying = Nullable.GetUnderlyingType(t);
                var val = underlying.RandomValue(stringValueAllowEmpty);

                var cons = t.GetConstructor(new[] { underlying });

                return cons.Invoke(new object[] { val });
            }

            if (t.IsEnum)
            {
                var allValues = Enum.GetValues(t);
                var ix = Rand.Next(allValues.Length);

                return allValues.GetValue(ix);
            }

            if (t.IsArray)
            {
                var valType = t.GetElementType();
                var len = Rand.Next(20, 50);
                var ret = Array.CreateInstance(valType, len);
                //var add = t.GetMethod("SetValue");
                for (var i = 0; i < len; i++)
                {
                    var elem = valType.RandomValue(stringValueAllowEmpty);
                    ret.SetValue(elem, i);
                }

                return ret;
            }

            if (t.IsGenericType)
            {
                var defind = t.GetGenericTypeDefinition();
                if (defind == typeof(HashSet<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");
                    var contains = t.GetMethod("Contains");

                    var len = Rand.Next(20, 50);
                    for (var i = 0; i < len; i++)
                    {
                        var elem = valType.RandomValue(stringValueAllowEmpty);
                        while (elem == null || (bool)contains.Invoke(ret, new object[] { elem }))
                            elem = valType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { elem });
                    }

                    return ret;
                }
                if (defind == typeof(Dictionary<,>))
                {
                    var keyType = t.GetGenericArguments()[0];
                    var valType = t.GetGenericArguments()[1];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");
                    var contains = t.GetMethod("ContainsKey");

                    var len = Rand.Next(20, 50);
                    if (keyType == typeof(Boolean))
                        len = 2;
                    for (var i = 0; i < len; i++)
                    {
                        var val = valType.RandomValue(stringValueAllowEmpty);
                        var key = keyType.RandomValue(stringValueAllowEmpty);
                       

                        while (key == null || (bool)contains.Invoke(ret, new object[] { key }))
                            key = keyType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { key, val });
                    }

                    return ret;
                }
                if (defind == typeof(List<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");

                    var len = Rand.Next(20, 50);
                    for (var i = 0; i < len; i++)
                    {
                        var elem = valType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { elem });
                    }

                    return ret;
                }
                if (defind == typeof(ArraySegment<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ary = valType.MakeArrayType().RandomValue(stringValueAllowEmpty);
                    var lenT = ary.GetType().GetProperty("Length");
                    var offset = Rand.Next(0, (int)lenT.GetValue(ary) - 1);
                    var len = (int)lenT.GetValue(ary) - offset;

                    return Activator.CreateInstance(t, ary, offset, len);
                }
            }

            if (t == typeof(Guid))
                return Guid.NewGuid();

            if (t == typeof(object))
            {
                var code = Rand.Next(0, 9);
                switch (code)
                {
                    case 0:
                        return RandomValue<int>();
                    case 1:
                        return RandomValue<long>();
                    case 2:
                        return RandomValue<Char>();
                    case 3:
                        return RandomValue<DateTime>();
                    case 4:
                        return RandomValue<string>(stringValueAllowEmpty);
                    case 5:
                        return RandomValue<Guid>();
                    case 6:
                        return RandomValue<decimal>();
                    case 7:
                        return RandomValue<double>();
                    case 8:
                        return RandomValue<float>();
                    default:
                        return RandomValue<short>();
                }
            }

            //model
            var retObj = Activator.CreateInstance(t);
            foreach (var p in t.GetFields())
            {
                //if (Rand.Next(5) == 0) continue;

                var fieldType = p.FieldType;

                p.SetValue(retObj, fieldType.RandomValue(stringValueAllowEmpty));
            }

            foreach (var p in t.GetProperties())
            {
                //if (Rand.Next(5) == 0) continue;
                if (p.CanWrite && p.CanRead)
                {
                    var fieldType = p.PropertyType;

                    p.SetValue(retObj, fieldType.RandomValue(stringValueAllowEmpty));
                }
            }

            return retObj;
        }

19 View Source File : DotNetToJScript.cs
License : MIT License
Project Creator : 1y0n

static object BuildLoaderDelegateMscorlib(byte[] replacedembly)
        {
            Delegate res = Delegate.CreateDelegate(typeof(Converter<byte[], replacedembly>),
                replacedembly,
                typeof(replacedembly).GetMethod("Load", new Type[] { typeof(byte[]), typeof(byte[]) }));

            HeaderHandler d = new HeaderHandler(Convert.ToString);

            d = (HeaderHandler)Delegate.Combine(d, (Delegate)d.Clone());
            d = (HeaderHandler)Delegate.Combine(d, (Delegate)d.Clone());

            FieldInfo fi = typeof(MulticastDelegate).GetField("_invocationList", BindingFlags.NonPublic | BindingFlags.Instance);

            object[] invoke_list = d.GetInvocationList();
            invoke_list[1] = res;
            fi.SetValue(d, invoke_list);

            d = (HeaderHandler)Delegate.Remove(d, (Delegate)invoke_list[0]);
            d = (HeaderHandler)Delegate.Remove(d, (Delegate)invoke_list[2]);

            return d;
        }

19 View Source File : RandomHelper.cs
License : MIT License
Project Creator : 1996v

public static object RandomValue(this Type t, bool stringValueAllowEmpty = true)
        {
            if (t.IsPrimitive)
            {
                if (t == typeof(byte))
                {
                    return (byte)(Rand.Next(byte.MaxValue - byte.MinValue + 1) + byte.MinValue);
                }

                if (t == typeof(sbyte))
                {
                    return (sbyte)(Rand.Next(sbyte.MaxValue - sbyte.MinValue + 1) + sbyte.MinValue);
                }

                if (t == typeof(short))
                {
                    return (short)(Rand.Next(short.MaxValue - short.MinValue + 1) + short.MinValue);
                }

                if (t == typeof(ushort))
                {
                    return (ushort)(Rand.Next(ushort.MaxValue - ushort.MinValue + 1) + ushort.MinValue);
                }

                if (t == typeof(int))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToInt32(bytes, 0);
                }

                if (t == typeof(uint))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToUInt32(bytes, 0);
                }

                if (t == typeof(long))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToInt64(bytes, 0);
                }

                if (t == typeof(ulong))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToUInt64(bytes, 0);
                }

                if (t == typeof(float))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    var f = BitConverter.ToSingle(bytes, 0);
                    if (float.IsNaN(f))
                        f = (float)RandomValue<short>();
                    return f;
                }

                if (t == typeof(double))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    var d = BitConverter.ToDouble(bytes, 0);
                    if (double.IsNaN(d))
                        d = (double)RandomValue<short>();
                    return d;
                }

                if (t == typeof(char))
                {
                    var roll = Rand.Next(ASCII.Length);

                    return ASCII[roll];
                }

                if (t == typeof(bool))
                {
                    return (Rand.Next(2) == 1);
                }

                throw new InvalidOperationException();
            }

            if (t == typeof(decimal))
            {
                return new decimal((int)typeof(int).RandomValue(), (int)typeof(int).RandomValue(), (int)typeof(int).RandomValue(), false, 28);
            }

            if (t == typeof(string))
            {
                int start = stringValueAllowEmpty ? 0 : 1;
                var len = Rand.Next(start, 28);
                var c = new char[len];
                for (var i = 0; i < c.Length; i++)
                {
                    c[i] = (char)typeof(char).RandomValue();
                }

                return new string(c);
            }

            if (t == typeof(DateTime))
            {
                var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

                var bytes = new byte[4];
                Rand.NextBytes(bytes);

                var secsOffset = BitConverter.ToInt32(bytes, 0);

                var retDate = epoch.AddSeconds(secsOffset);

                return retDate;
            }

            if (t == typeof(TimeSpan))
            {
                return new TimeSpan(RandomValue<DateTime>().Ticks);
            }

            if (t == typeof(DataTable))
            {
                DataTable dt = new DataTable();
                int coluCount = Rand.Next(10, 30);
                for (int i = 0; i < coluCount; i++)
                {
                    dt.Columns.Add(RandomHelper.RandomValue<string>(false), typeof(object));
                }
                int rowCount = Rand.Next(20, 50);
                for (int i = 0; i < rowCount; i++)
                {
                    var row = new object[coluCount];
                    for (int zi = 0; zi < coluCount; zi++)
                    {
                        row[zi] = RandomHelper.RandomValue<object>();
                    }
                    dt.Rows.Add(row);
                }
                return dt;
            }

            if (t.IsNullable())
            {
                // leave it unset
                if (Rand.Next(2) == 0)
                {
                    // null!
                    return Activator.CreateInstance(t);
                }

                var underlying = Nullable.GetUnderlyingType(t);
                var val = underlying.RandomValue(stringValueAllowEmpty);

                var cons = t.GetConstructor(new[] { underlying });

                return cons.Invoke(new object[] { val });
            }

            if (t.IsEnum)
            {
                var allValues = Enum.GetValues(t);
                var ix = Rand.Next(allValues.Length);

                return allValues.GetValue(ix);
            }

            if (t.IsArray)
            {
                var valType = t.GetElementType();
                var len = Rand.Next(20, 50);
                var ret = Array.CreateInstance(valType, len);
                //var add = t.GetMethod("SetValue");
                for (var i = 0; i < len; i++)
                {
                    var elem = valType.RandomValue(stringValueAllowEmpty);
                    ret.SetValue(elem, i);
                }

                return ret;
            }

            if (t.IsGenericType)
            {
                var defind = t.GetGenericTypeDefinition();
                if (defind == typeof(HashSet<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");
                    var contains = t.GetMethod("Contains");

                    var len = Rand.Next(20, 50);
                    for (var i = 0; i < len; i++)
                    {
                        var elem = valType.RandomValue(stringValueAllowEmpty);
                        while (elem == null || (bool)contains.Invoke(ret, new object[] { elem }))
                            elem = valType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { elem });
                    }

                    return ret;
                }
                if (defind == typeof(Dictionary<,>))
                {
                    var keyType = t.GetGenericArguments()[0];
                    var valType = t.GetGenericArguments()[1];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");
                    var contains = t.GetMethod("ContainsKey");

                    var len = Rand.Next(20, 50);
                    if (keyType == typeof(Boolean))
                        len = 2;
                    for (var i = 0; i < len; i++)
                    {
                        var val = valType.RandomValue(stringValueAllowEmpty);
                        var key = keyType.RandomValue(stringValueAllowEmpty);
                        while (key == null || (bool)contains.Invoke(ret, new object[] { key }))
                            key = keyType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { key, val });
                    }

                    return ret;
                }
                if (defind == typeof(List<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");

                    var len = Rand.Next(20, 50);
                    for (var i = 0; i < len; i++)
                    {
                        var elem = valType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { elem });
                    }

                    return ret;
                }
                if (defind == typeof(ArraySegment<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ary = valType.MakeArrayType().RandomValue(stringValueAllowEmpty);
                    var lenT = ary.GetType().GetProperty("Length");
                    var offset = Rand.Next(0, (int)lenT.GetValue(ary) - 1);
                    var len = (int)lenT.GetValue(ary) - offset;

                    return Activator.CreateInstance(t, ary, offset, len);
                }
            }

            if (t == typeof(Guid))
                return Guid.NewGuid();

            if (t == typeof(object))
            {
                var code = Rand.Next(0, 9);
                switch (code)
                {
                    case 0:
                        return RandomValue<int>();
                    case 1:
                        return RandomValue<long>();
                    case 2:
                        return RandomValue<Char>();
                    case 3:
                        return RandomValue<DateTime>();
                    case 4:
                        return RandomValue<string>(stringValueAllowEmpty);
                    case 5:
                        return RandomValue<Guid>();
                    case 6:
                        return RandomValue<decimal>();
                    case 7:
                        return RandomValue<double>();
                    case 8:
                        return RandomValue<float>();
                    default:
                        return RandomValue<short>();
                }
            }

            //model
            var retObj = Activator.CreateInstance(t);
            foreach (var p in t.GetFields())
            {
                //if (Rand.Next(5) == 0) continue;

                var fieldType = p.FieldType;

                p.SetValue(retObj, fieldType.RandomValue(stringValueAllowEmpty));
            }

            foreach (var p in t.GetProperties())
            {
                //if (Rand.Next(5) == 0) continue;
                if (p.CanWrite && p.CanRead)
                {
                    var fieldType = p.PropertyType;

                    p.SetValue(retObj, fieldType.RandomValue(stringValueAllowEmpty));
                }
            }

            return retObj;
        }

19 View Source File : RepositoryDbContext.cs
License : MIT License
Project Creator : 2881099

public override IDbSet Set(Type enreplacedyType) {
			if (_dicSet.ContainsKey(enreplacedyType)) return _dicSet[enreplacedyType];

			var tb = _orm.CodeFirst.GetTableByEnreplacedy(enreplacedyType);
			if (tb == null) return null;

			object repos = _repos;
			if (enreplacedyType != _repos.EnreplacedyType) {
				repos = Activator.CreateInstance(typeof(DefaultRepository<,>).MakeGenericType(enreplacedyType, typeof(int)), _repos.Orm);
				(repos as IBaseRepository).UnitOfWork = _repos.UnitOfWork;
				GetRepositoryDbField(enreplacedyType).SetValue(repos, this);

				typeof(RepositoryDbContext).GetMethod("SetRepositoryDataFilter").MakeGenericMethod(_repos.EnreplacedyType)
					.Invoke(null, new object[] { repos, _repos });
			}

			var sd = Activator.CreateInstance(typeof(RepositoryDbSet<>).MakeGenericType(enreplacedyType), repos) as IDbSet;
			if (enreplacedyType != typeof(object)) _dicSet.Add(enreplacedyType, sd);
			return sd;
		}

19 View Source File : InternalExtensions.cs
License : MIT License
Project Creator : 2881099

public static void SetPropertyOrFieldValue(this Type enreplacedyType, object enreplacedy, string propertyName, object value)
    {
        if (enreplacedy == null) return;
        if (enreplacedyType == null) enreplacedyType = enreplacedy.GetType();

        if (SetSetPropertyOrFieldValueSupportExpressionTreeFlag == 0)
        {
            if (GetPropertiesDictIgnoreCase(enreplacedyType).TryGetValue(propertyName, out var prop))
            {
                prop.SetValue(enreplacedy, value, null);
                return;
            }
            if (GetFieldsDictIgnoreCase(enreplacedyType).TryGetValue(propertyName, out var field))
            {
                field.SetValue(enreplacedy, value);
                return;
            }
            throw new Exception($"The property({propertyName}) was not found in the type({enreplacedyType.DisplayCsharp()})");
        }

        Action<object, string, object> func = null;
        try
        {
            func = _dicSetPropertyOrFieldValue
                .GetOrAdd(enreplacedyType, et => new ConcurrentDictionary<string, Action<object, string, object>>())
                .GetOrAdd(propertyName, pn =>
                {
                    var t = enreplacedyType;
                    MemberInfo memberinfo = enreplacedyType.GetPropertyOrFieldIgnoreCase(pn);
                    var parm1 = Expression.Parameter(typeof(object));
                    var parm2 = Expression.Parameter(typeof(string));
                    var parm3 = Expression.Parameter(typeof(object));
                    var var1Parm = Expression.Variable(t);
                    var exps = new List<Expression>(new Expression[] {
                            Expression.replacedign(var1Parm, Expression.TypeAs(parm1, t))
                    });
                    if (memberinfo != null)
                    {
                        exps.Add(
                            Expression.replacedign(
                                Expression.MakeMemberAccess(var1Parm, memberinfo),
                                Expression.Convert(
                                    parm3,
                                    memberinfo.GetPropertyOrFieldType()
                                )
                            )
                        );
                    }
                    return Expression.Lambda<Action<object, string, object>>(Expression.Block(new[] { var1Parm }, exps), new[] { parm1, parm2, parm3 }).Compile();
                });
        }
        catch
        {
            System.Threading.Interlocked.Exchange(ref SetSetPropertyOrFieldValueSupportExpressionTreeFlag, 0);
            SetPropertyOrFieldValue(enreplacedyType, enreplacedy, propertyName, value);
            return;
        }
        func(enreplacedy, propertyName, value);
    }

19 View Source File : ObjectTypeUtil.cs
License : MIT License
Project Creator : 404Lcc

public static void Draw(object obj, int indentLevel)
        {
            EditorGUILayout.BeginVertical();
            EditorGUI.indentLevel = indentLevel;
            string replacedemblyName = string.Empty;
            switch (Path.GetFileNameWithoutExtension(obj.GetType().replacedembly.ManifestModule.Name))
            {
                case "Unity.Model":
                    replacedemblyName = "Unity.Model";
                    break;
                case "Unity.Hotfix":
                    replacedemblyName = "Unity.Hotfix";
                    break;
                case "ILRuntime":
                    replacedemblyName = "Unity.Hotfix";
                    break;
            }
            if (replacedemblyName == "Unity.Model")
            {
                FieldInfo[] fieldInfos = obj.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy);
                foreach (FieldInfo item in fieldInfos)
                {
                    object value = item.GetValue(obj);
                    Type type = item.FieldType;
                    if (item.IsDefined(typeof(HideInInspector), false))
                    {
                        continue;
                    }
                    if (type.IsDefined(typeof(HideInInspector), false))
                    {
                        continue;
                    }
                    if (objectObjectTypes.ContainsKey((obj, item)))
                    {
                        ObjectObjectType objectObjectType = (ObjectObjectType)objectObjectTypes[(obj, item)];
                        objectObjectType.Draw(type, item.Name, value, null, indentLevel);
                        continue;
                    }
                    if ((item.IsDefined(typeof(SerializeField), false) || type.IsDefined(typeof(SerializeField), false)) && type.replacedembly.ManifestModule.Name == "Unity.Model.dll")
                    {
                        ObjectObjectType objectObjectType = new ObjectObjectType();
                        if (value == null)
                        {
                            object instance = Activator.CreateInstance(type);
                            objectObjectType.Draw(type, item.Name, instance, null, indentLevel);
                            item.SetValue(obj, instance);
                        }
                        else
                        {
                            objectObjectType.Draw(type, item.Name, value, null, indentLevel);
                        }
                        objectObjectTypes.Add((obj, item), objectObjectType);
                        continue;
                    }
                    if (listObjectTypes.ContainsKey((obj, item)))
                    {
                        ListObjectType listObjectType = (ListObjectType)listObjectTypes[(obj, item)];
                        listObjectType.Draw(type, item.Name, value, null, indentLevel);
                        continue;
                    }
                    if (type.GetInterface("IList") != null)
                    {
                        ListObjectType listObjectType = new ListObjectType();
                        if (value == null)
                        {
                            continue;
                        }
                        listObjectType.Draw(type, item.Name, value, null, indentLevel);
                        listObjectTypes.Add((obj, item), listObjectType);
                        continue;
                    }
                    foreach (IObjectType objectTypeItem in objectList)
                    {
                        if (!objectTypeItem.IsType(type))
                        {
                            continue;
                        }
                        string fieldName = item.Name;
                        if (fieldName.Contains("clrInstance") || fieldName.Contains("Boxed"))
                        {
                            continue;
                        }
                        if (fieldName.Length > 17 && fieldName.Contains("k__BackingField"))
                        {
                            fieldName = fieldName.Substring(1, fieldName.Length - 17);
                        }
                        value = objectTypeItem.Draw(type, fieldName, value, null);
                        item.SetValue(obj, value);
                    }
                }
            }
            else
            {
#if ILRuntime
                FieldInfo[] fieldInfos = ILRuntimeManager.Instance.appdomain.LoadedTypes[obj.ToString()].ReflectionType.GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy);
                foreach (FieldInfo item in fieldInfos)
                {
                    object value = item.GetValue(obj);
                    if (item.FieldType is ILRuntimeWrapperType)
                    {
                        //基础类型绘制
                        Type type = ((ILRuntimeWrapperType)item.FieldType).RealType;
                        if (item.IsDefined(typeof(HideInInspector), false))
                        {
                            continue;
                        }
                        if (type.IsDefined(typeof(HideInInspector), false))
                        {
                            continue;
                        }
                        if (listObjectTypes.ContainsKey((obj, item)))
                        {
                            ListObjectType listObjectType = (ListObjectType)listObjectTypes[(obj, item)];
                            listObjectType.Draw(type, item.Name, value, null, indentLevel);
                            continue;
                        }
                        if (type.GetInterface("IList") != null)
                        {
                            ListObjectType listObjectType = new ListObjectType();
                            if (value == null)
                            {
                                continue;
                            }
                            listObjectType.Draw(type, item.Name, value, null, indentLevel);
                            listObjectTypes.Add((obj, item), listObjectType);
                            continue;
                        }
                        foreach (IObjectType objectTypeItem in objectList)
                        {
                            if (!objectTypeItem.IsType(type))
                            {
                                continue;
                            }
                            string fieldName = item.Name;
                            if (fieldName.Contains("clrInstance") || fieldName.Contains("Boxed"))
                            {
                                continue;
                            }
                            if (fieldName.Length > 17 && fieldName.Contains("k__BackingField"))
                            {
                                fieldName = fieldName.Substring(1, fieldName.Length - 17);
                            }
                            value = objectTypeItem.Draw(type, fieldName, value, null);
                            item.SetValue(obj, value);
                        }
                    }
                    else
                    {
                        //自定义类型绘制
                        Type type = item.FieldType;
                        if (item.IsDefined(typeof(HideInInspector), false))
                        {
                            continue;
                        }
                        if (type.IsDefined(typeof(HideInInspector), false))
                        {
                            continue;
                        }
                        if (objectObjectTypes.ContainsKey((obj, item)))
                        {
                            ObjectObjectType objectObjectType = (ObjectObjectType)objectObjectTypes[(obj, item)];
                            objectObjectType.Draw(type, item.Name, value, null, indentLevel);
                            continue;
                        }
                        if ((item.IsDefined(typeof(SerializeField), false) || type.IsDefined(typeof(SerializeField), false)) && type.replacedembly.ManifestModule.Name == "ILRuntime.dll")
                        {
                            ObjectObjectType objectObjectType = new ObjectObjectType();
                            if (value == null)
                            {
                                object instance = ILRuntimeManager.Instance.appdomain.Instantiate(type.ToString());
                                objectObjectType.Draw(type, item.Name, instance, null, indentLevel);
                                item.SetValue(obj, instance);
                            }
                            else
                            {
                                objectObjectType.Draw(type, item.Name, value, null, indentLevel);
                            }
                            objectObjectTypes.Add((obj, item), objectObjectType);
                            continue;
                        }
                    }
                }
#else
                FieldInfo[] fieldInfos = obj.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy);
                foreach (FieldInfo item in fieldInfos)
                {
                    object value = item.GetValue(obj);
                    Type type = item.FieldType;
                    if (item.IsDefined(typeof(HideInInspector), false))
                    {
                        continue;
                    }
                    if (type.IsDefined(typeof(HideInInspector), false))
                    {
                        continue;
                    }
                    if (objectObjectTypes.ContainsKey((obj, item)))
                    {
                        ObjectObjectType objectObjectType = (ObjectObjectType)objectObjectTypes[(obj, item)];
                        objectObjectType.Draw(type, item.Name, value, null, indentLevel);
                        continue;
                    }
                    if ((item.IsDefined(typeof(SerializeField), false) || type.IsDefined(typeof(SerializeField), false)) && type.replacedembly.ManifestModule.Name == "Unity.Hotfix.dll")
                    {
                        ObjectObjectType objectObjectType = new ObjectObjectType();
                        if (value == null)
                        {
                            object instance = Activator.CreateInstance(type);
                            objectObjectType.Draw(type, item.Name, instance, null, indentLevel);
                            item.SetValue(obj, instance);
                        }
                        else
                        {
                            objectObjectType.Draw(type, item.Name, value, null, indentLevel);
                        }
                        objectObjectTypes.Add((obj, item), objectObjectType);
                        continue;
                    }
                    if (listObjectTypes.ContainsKey((obj, item)))
                    {
                        ListObjectType listObjectType = (ListObjectType)listObjectTypes[(obj, item)];
                        listObjectType.Draw(type, item.Name, value, null, indentLevel);
                        continue;
                    }
                    if (type.GetInterface("IList") != null)
                    {
                        ListObjectType listObjectType = new ListObjectType();
                        if (value == null)
                        {
                            continue;
                        }
                        listObjectType.Draw(type, item.Name, value, null, indentLevel);
                        listObjectTypes.Add((obj, item), listObjectType);
                        continue;
                    }
                    foreach (IObjectType objectTypeItem in objectList)
                    {
                        if (!objectTypeItem.IsType(type))
                        {
                            continue;
                        }
                        string fieldName = item.Name;
                        if (fieldName.Contains("clrInstance") || fieldName.Contains("Boxed"))
                        {
                            continue;
                        }
                        if (fieldName.Length > 17 && fieldName.Contains("k__BackingField"))
                        {
                            fieldName = fieldName.Substring(1, fieldName.Length - 17);
                        }
                        value = objectTypeItem.Draw(type, fieldName, value, null);
                        item.SetValue(obj, value);
                    }
                }
#endif
                EditorGUI.indentLevel = indentLevel;
                EditorGUILayout.EndVertical();
            }
        }

19 View Source File : CommandManager.cs
License : MIT License
Project Creator : 404Lcc

public void AddCommands(CommandData[] commandDatas)
        {
            if (commandDatas == null) return;
            List<CommandData> targetList = new List<CommandData>();
            foreach (CommandData item in commandDatas)
            {
                CommandData target;
                switch (item.dataType)
                {
                    default:
                        target = new CommandData();
                        break;
                }
                FieldInfo[] fieldInfos = target.GetType().GetFields();
                foreach (FieldInfo fieldinfoitem in fieldInfos)
                {
                    fieldinfoitem.SetValue(target, fieldinfoitem.GetValue(item));
                }
                targetList.Add(target);
            }
            commandDataList.AddRange(targetList.ToArray());
        }

19 View Source File : CommandManager.cs
License : MIT License
Project Creator : 404Lcc

public void AddCommand(CommandData commandData)
        {
            if (commandData == null) return;
            CommandData target;
            switch (commandData.dataType)
            {
                default:
                    target = new CommandData();
                    break;
            }
            FieldInfo[] fieldInfos = target.GetType().GetFields();
            foreach (FieldInfo item in fieldInfos)
            {
                item.SetValue(target, item.GetValue(commandData));
            }
            commandDataList.Add(target);
        }

19 View Source File : AObjectBase.cs
License : MIT License
Project Creator : 404Lcc

public void AutoReference(Transform transform, Dictionary<string, FieldInfo> fieldInfoDict)
        {
            string name = transform.name.ToLower();
            if (fieldInfoDict.ContainsKey(name))
            {
                if (fieldInfoDict[name].FieldType.Equals(typeof(GameObject)))
                {
                    fieldInfoDict[name].SetValue(this, transform.gameObject);
                }
                else if (fieldInfoDict[name].FieldType.Equals(typeof(Transform)))
                {
                    fieldInfoDict[name].SetValue(this, transform);
                }
                else
                {
                    fieldInfoDict[name].SetValue(this, transform.GetComponent(fieldInfoDict[name].FieldType));
                }
            }
            for (int i = 0; i < transform.childCount; i++)
            {
                AutoReference(transform.GetChild(i), fieldInfoDict);
            }
        }

19 View Source File : JsonMapper.cs
License : MIT License
Project Creator : 404Lcc

private static object ReadValue (Type inst_type, JsonReader reader)
        {
            reader.Read ();

            if (reader.Token == JsonToken.ArrayEnd)
                return null;

            //ILRuntime doesn't support nullable valuetype
            Type underlying_type = inst_type;//Nullable.GetUnderlyingType(inst_type);
            Type value_type = inst_type;

            if (reader.Token == JsonToken.Null) {
                if (inst_type.IsClreplaced || underlying_type != null) {
                    return null;
                }

                throw new JsonException (String.Format (
                            "Can't replacedign null to an instance of type {0}",
                            inst_type));
            }

            if (reader.Token == JsonToken.Double ||
                reader.Token == JsonToken.Int ||
                reader.Token == JsonToken.Long ||
                reader.Token == JsonToken.String ||
                reader.Token == JsonToken.Boolean) {

                Type json_type = reader.Value.GetType();
                var vt = value_type is ILRuntime.Reflection.ILRuntimeWrapperType ? ((ILRuntime.Reflection.ILRuntimeWrapperType)value_type).CLRType.TypeForCLR : value_type;

                if (vt.IsreplacedignableFrom(json_type))
                    return reader.Value;
                if (vt is ILRuntime.Reflection.ILRuntimeType && ((ILRuntime.Reflection.ILRuntimeType)vt).ILType.IsEnum)
                {
                    if (json_type == typeof(int) || json_type == typeof(long) || json_type == typeof(short) || json_type == typeof(byte))
                        return reader.Value;
                }
                // If there's a custom importer that fits, use it
                if (custom_importers_table.ContainsKey (json_type) &&
                    custom_importers_table[json_type].ContainsKey (
                        vt)) {

                    ImporterFunc importer =
                        custom_importers_table[json_type][vt];

                    return importer (reader.Value);
                }

                // Maybe there's a base importer that works
                if (base_importers_table.ContainsKey (json_type) &&
                    base_importers_table[json_type].ContainsKey (
                        vt)) {

                    ImporterFunc importer =
                        base_importers_table[json_type][vt];

                    return importer (reader.Value);
                }

                // Maybe it's an enum
                if (vt.IsEnum)
                    return Enum.ToObject (vt, reader.Value);

                // Try using an implicit conversion operator
                MethodInfo conv_op = GetConvOp (vt, json_type);

                if (conv_op != null)
                    return conv_op.Invoke (null,
                                           new object[] { reader.Value });

                // No luck
                throw new JsonException (String.Format (
                        "Can't replacedign value '{0}' (type {1}) to type {2}",
                        reader.Value, json_type, inst_type));
            }

            object instance = null;

            if (reader.Token == JsonToken.ArrayStart) {

                AddArrayMetadata (inst_type);
                ArrayMetadata t_data = array_metadata[inst_type];

                if (! t_data.IsArray && ! t_data.IsList)
                    throw new JsonException (String.Format (
                            "Type {0} can't act as an array",
                            inst_type));

                IList list;
                Type elem_type;

                if (! t_data.IsArray) {
                    list = (IList) Activator.CreateInstance (inst_type);
                    elem_type = t_data.ElementType;
                } else {
                    list = new ArrayList ();
                    elem_type = inst_type.GetElementType ();
                }

                while (true) {
                    object item = ReadValue (elem_type, reader);
                    if (item == null && reader.Token == JsonToken.ArrayEnd)
                        break;
                    var rt = elem_type is ILRuntime.Reflection.ILRuntimeWrapperType ? ((ILRuntime.Reflection.ILRuntimeWrapperType)elem_type).RealType : elem_type;
                    if (elem_type is ILRuntime.Reflection.ILRuntimeType && ((ILRuntime.Reflection.ILRuntimeType)elem_type).ILType.IsEnum)
                    {
                        item = (int) item;
                    }
                    else
                    {
                        item = rt.CheckCLRTypes(item);            
                    }
                    list.Add (item);         
                    
                }

                if (t_data.IsArray) {
                    int n = list.Count;
                    instance = Array.CreateInstance (elem_type, n);

                    for (int i = 0; i < n; i++)
                        ((Array) instance).SetValue (list[i], i);
                } else
                    instance = list;

            } else if (reader.Token == JsonToken.ObjectStart)
            {
                AddObjectMetadata(value_type);
                ObjectMetadata t_data = object_metadata[value_type];
                if (value_type is ILRuntime.Reflection.ILRuntimeType)
                    instance = ((ILRuntime.Reflection.ILRuntimeType) value_type).ILType.Instantiate();
                else
                    instance = Activator.CreateInstance(value_type);
                bool isIntKey = t_data.IsDictionary && value_type.GetGenericArguments()[0] == typeof(int);
                while (true)
                {
                    reader.Read();

                    if (reader.Token == JsonToken.ObjectEnd)
                        break;

                    string key = (string) reader.Value;

                    if (t_data.Properties.ContainsKey(key))
                    {
                        PropertyMetadata prop_data =
                            t_data.Properties[key];

                        if (prop_data.IsField)
                        {
                            ((FieldInfo) prop_data.Info).SetValue(
                                instance, ReadValue(prop_data.Type, reader));
                        }
                        else
                        {
                            PropertyInfo p_info =
                                (PropertyInfo) prop_data.Info;

                            if (p_info.CanWrite)
                                p_info.SetValue(
                                    instance,
                                    ReadValue(prop_data.Type, reader),
                                    null);
                            else
                                ReadValue(prop_data.Type, reader);
                        }

                    }
                    else
                    {
                        if (!t_data.IsDictionary)
                        {

                            if (!reader.SkipNonMembers)
                            {
                                throw new JsonException(String.Format(
                                    "The type {0} doesn't have the " +
                                    "property '{1}'",
                                    inst_type, key));
                            }
                            else
                            {
                                ReadSkip(reader);
                                continue;
                            }
                        }

                        var dict = ((IDictionary) instance);
                        var elem_type = t_data.ElementType;
                        object readValue = ReadValue(elem_type, reader);
                        var rt = t_data.ElementType is ILRuntime.Reflection.ILRuntimeWrapperType
                            ? ((ILRuntime.Reflection.ILRuntimeWrapperType) t_data.ElementType).RealType
                            : t_data.ElementType;
                        //value 是枚举的情况没处理,毕竟少
                        if (isIntKey)
                        {
                            var dictValueType = value_type.GetGenericArguments()[1];
                            IConvertible convertible = dictValueType as IConvertible;
                            if (convertible == null)
                            {
                                //自定义类型扩展
                                if (dictValueType == typeof(double)) //CheckCLRTypes() 没有double,也可以修改ilruntime源码实现
                                {
                                    var v = Convert.ChangeType(readValue.ToString(), dictValueType);
                                    dict.Add(Convert.ToInt32(key), v);
                                }
                                else
                                {
                                    readValue = rt.CheckCLRTypes(readValue);
                                    dict.Add(Convert.ToInt32(key), readValue);
                                    // throw new JsonException (String.Format("The type {0} doesn't not support",dictValueType));
                                }
                            }
                            else
                            {
                                var v = Convert.ChangeType(readValue, dictValueType);
                                dict.Add(Convert.ToInt32(key), v);
                            }
                        }
                        else
                        {
                            readValue = rt.CheckCLRTypes(readValue);
                            dict.Add(key, readValue);
                        }
                    }

                }
            }

            return instance;
        }

19 View Source File : FieldDecorator.cs
License : MIT License
Project Creator : 404Lcc

public override object Read(object value, ProtoReader source)
        {
            Helpers.Debugreplacedert(value != null);
            object newValue = Tail.Read((Tail.RequiresOldValue ? field.GetValue(value) : null), source);
            if(newValue != null) field.SetValue(value,newValue);
            return null;
        }

19 View Source File : JSONParser.cs
License : MIT License
Project Creator : 5minlab

static object ParseObject(Type type, string json) {
            object instance = FormatterServices.GetUninitializedObject(type);

            //The list is split into key/value pairs only, this means the split must be divisible by 2 to be valid JSON
            List<string> elems = Split(json);
            if (elems.Count % 2 != 0)
                return instance;

            Dictionary<string, FieldInfo> nameToField;
            Dictionary<string, PropertyInfo> nameToProperty;
            if (!fieldInfoCache.TryGetValue(type, out nameToField)) {
                nameToField = type.GetFields().Where(field => field.IsPublic).ToDictionary(field => field.Name);
                fieldInfoCache.Add(type, nameToField);
            }
            if (!propertyInfoCache.TryGetValue(type, out nameToProperty)) {
                nameToProperty = type.GetProperties().ToDictionary(p => p.Name);
                propertyInfoCache.Add(type, nameToProperty);
            }

            for (int i = 0; i < elems.Count; i += 2) {
                if (elems[i].Length <= 2)
                    continue;
                string key = elems[i].Substring(1, elems[i].Length - 2);
                string value = elems[i + 1];

                FieldInfo fieldInfo;
                PropertyInfo propertyInfo;
                if (nameToField.TryGetValue(key, out fieldInfo))
                    fieldInfo.SetValue(instance, ParseValue(fieldInfo.FieldType, value));
                else if (nameToProperty.TryGetValue(key, out propertyInfo))
                    propertyInfo.SetValue(instance, ParseValue(propertyInfo.PropertyType, value), null);
            }

            return instance;
        }

19 View Source File : NotchSolutionDebugger.cs
License : MIT License
Project Creator : 5argon

public void Export()
    {
        device = new SimulationDevice();

        device.Meta = new MetaData();
        device.Meta.friendlyName = export.GetComponentInChildren<InputField>().text;

        device.SystemInfo = new SystemInfoData() { GraphicsDependentData = new GraphicsDependentSystemInfoData[1] { new GraphicsDependentSystemInfoData() } };
        foreach (var property in typeof(SystemInfo).GetProperties(BindingFlags.Public | BindingFlags.Static))
        {
            var prop = typeof(SystemInfoData).GetField(property.Name);
            if (prop != null) prop.SetValue(device.SystemInfo, property.GetValue(null));
            else
            {
                prop = typeof(GraphicsDependentSystemInfoData).GetField(property.Name);
                if (prop != null) prop.SetValue(device.SystemInfo.GraphicsDependentData[0], property.GetValue(null));
            }
        }

        device.Screens = new ScreenData[1];
        for (int i = 0; i < device.Screens.Length; i++)
        {
            var screen = new ScreenData();
            screen.width = Screen.width;
            screen.height = Screen.height;
            //screen.navigationBarHeight = 0;
            screen.orientations = new Dictionary<ScreenOrientation, OrientationDependentData>();
            screen.dpi = Screen.dpi;
            device.Screens[i] = screen;
            StartCoroutine(screenData(screen));
        }

        menu = Menu.Extracting;
    }

19 View Source File : CometaryExtensions.cs
License : MIT License
Project Creator : 71

public static T Construct<T>(this AttributeData attribute)
        {
            if (attribute == null)
                throw new ArgumentNullException(nameof(attribute));

            // Make args array
            ImmutableArray<TypedConstant> constantArgs = attribute.ConstructorArguments;
            object[] args = new object[constantArgs.Length];

            for (int i = 0; i < constantArgs.Length; i++)
            {
                args[i] = constantArgs[i].GetValue();
            }

            // Find ctor, and invoke it
            ConstructorInfo constructor = attribute.AttributeConstructor.GetCorrespondingMethod() as ConstructorInfo;

            if (constructor == null)
                throw new DiagnosticException($"Cannot find a constructor matching {attribute.AttributeConstructor}.", attribute.ApplicationSyntaxReference.ToLocation());

            T result = (T)constructor.Invoke(args);

            // Set named args
            var namedArgs = attribute.NamedArguments;

            if (namedArgs.Length == 0)
                return result;

            Type attrType = constructor.DeclaringType;

            for (int i = 0; i < namedArgs.Length; i++)
            {
                var namedArg = namedArgs[i];
                MemberInfo correspondingMember = attrType.GetMember(namedArg.Key, BindingFlags.Instance | BindingFlags.Public)[0];

                switch (correspondingMember)
                {
                    case PropertyInfo prop:
                        prop.SetValue(result, namedArg.Value.GetValue());
                        break;
                    case FieldInfo field:
                        field.SetValue(result, namedArg.Value.GetValue());
                        break;
                }
            }

            // Return fully constructed attr
            return result;
        }

19 View Source File : Helpers.cs
License : MIT License
Project Creator : 71

internal static void CopyTo<T>(this T from, T to) where T : clreplaced
        {
            // Find base type of both compilations
            TypeInfo fromType = from.GetType().GetTypeInfo();
            TypeInfo toType = to.GetType().GetTypeInfo();
            Type baseType;

            if (fromType.IsreplacedignableFrom(toType))
            {
                // ToCompilation inherits FromCompilation
                baseType = fromType.AsType();
            }
            else if (toType.IsreplacedignableFrom(fromType))
            {
                // FromCompilation inherits ToCompilation
                baseType = toType.AsType();
            }
            else
            {
                // No common type: find first common type
                baseType = FindCommonType(fromType.AsType(), toType.AsType());
            }

            // Copy fields from one compilation to the other
            foreach (FieldInfo field in baseType.GetAllFields())
            {
                if (field.IsStatic)
                    continue;

                field.SetValue(to, field.GetValue(from));
            }
        }

19 View Source File : CompilationProcessor.cs
License : MIT License
Project Creator : 71

public bool TryEditCompilation(CSharpCompilation compilation, CancellationToken cancellationToken, out CSharpCompilation modified, out object outputBuilder)
        {
            modified = compilation;

            if (!IsInitialized && !TryInitialize(compilation, cancellationToken) ||
                 IsInitialized && !IsInitializationSuccessful)
            {
                outputBuilder = null;
                return false;
            }

            // Recompute compilation if needed
            if (SharedStorage.TryGet(Helpers.RecomputeKey, out Pipeline<Func<CSharpParseOptions, CSharpParseOptions>> pipeline))
            {
                Func<CSharpParseOptions, CSharpParseOptions> del = pipeline.MakeDelegate(opts => opts);

                modified = modified.RecomputeCompilationWithOptions(del, cancellationToken);
            }

            List<CompilationEditor> editors = Editors;
            string step = "NotifyCompilationStart";

            // Run the compilation
            try
            {
                // Run the compilation
                for (int i = 0; i < editors.Count; i++)
                    editors[i].TriggerCompilationStart(compilation);

                step = "Preprocessing";

                foreach (var edit in CompilationPipeline)
                    modified = edit(modified, cancellationToken) ?? modified;

                step = "NotifyCompilationEnd";

                // Notify of end of compilation, and start of emission
                for (int i = 0; i < editors.Count; i++)
                    editors[i].TriggerCompilationEnd(compilation);

                step = "NotifyEmissionStart";

                for (int i = 0; i < editors.Count; i++)
                    editors[i].TriggerEmissionStart();

                step = "Processing";

                // Emit the replacedembly, and notify of start of emission
                object moduleBuilder = getModuleBuilder(modified);
                Type replacedemblySymbolInterf = typeof(IreplacedemblySymbol);

                FieldInfo replacedemblyField = moduleBuilder.GetType().GetAllFields()
                    .First(x => x.FieldType.GetInterfaces().Contains(replacedemblySymbolInterf));

                ISourcereplacedemblySymbol replacedemblySymbol = replacedemblyField.GetValue(moduleBuilder) as ISourcereplacedemblySymbol;
                ISourcereplacedemblySymbol originalreplacedembly = replacedemblySymbol;

                foreach (var edit in replacedemblyPipeline)
                    replacedemblySymbol = edit(replacedemblySymbol, cancellationToken) ?? replacedemblySymbol;

                step = "NotifyEmissionEnd";

                // Notify of overall end
                for (int i = 0; i < editors.Count; i++)
                    editors[i].TriggerEmissionEnd();

                step = "Continuing";

                // Copy modified replacedembly to builder
                if (!ReferenceEquals(originalreplacedembly, replacedemblySymbol))
                    replacedemblyField.SetValue(moduleBuilder, replacedemblySymbol);

                outputBuilder = moduleBuilder;
                return true;
            }
            catch (Exception e)
            {
                do
                {
                    if (e is DiagnosticException de)
                    {
                        AddDiagnostic(de.Diagnostic);
                    }
                    else if (e is AggregateException ae)
                    {
                        foreach (Exception ex in ae.InnerExceptions)
                        {
                            ReportDiagnostic(step, ex.Message, ex.Source);
                        }
                    }
                    else
                    {
                        ReportDiagnostic(step, e.Message, e.Source);
                    }
                }
                while ((e = e.InnerException) != null);
            }

            outputBuilder = null;
            return false;
        }

19 View Source File : FsmUtil.cs
License : GNU General Public License v3.0
Project Creator : a2659802

public static void ReplaceStringVariable(PlayMakerFSM fsm, string state, Dictionary<string, string> dict)
        {
            foreach (FsmState t in fsm.FsmStates)
            {
                bool found = false;
                if (t.Name != state && state != "") continue;
                foreach (FsmString str in (List<FsmString>) FsmStringParamsField.GetValue(t.ActionData))
                {
                    List<FsmString> val = new List<FsmString>();
                    if (dict.ContainsKey(str.Value))
                    {
                        val.Add(dict[str.Value]);
                        found = true;
                    }
                    else
                    {
                        val.Add(str);
                    }

                    if (val.Count > 0)
                    {
                        FsmStringParamsField.SetValue(t.ActionData, val);
                    }
                }

                if (found)
                {
                    t.LoadActions();
                }
            }
        }

19 View Source File : FsmUtil.cs
License : GNU General Public License v3.0
Project Creator : a2659802

public static void ReplaceStringVariable(PlayMakerFSM fsm, List<string> states, Dictionary<string, string> dict)
        {
            foreach (FsmState t in fsm.FsmStates)
            {
                bool found = false;
                if (!states.Contains(t.Name)) continue;
                foreach (FsmString str in (List<FsmString>) FsmStringParamsField.GetValue(t.ActionData))
                {
                    List<FsmString> val = new List<FsmString>();
                    if (dict.ContainsKey(str.Value))
                    {
                        val.Add(dict[str.Value]);
                        found = true;
                    }
                    else
                    {
                        val.Add(str);
                    }

                    if (val.Count > 0)
                    {
                        FsmStringParamsField.SetValue(t.ActionData, val);
                    }
                }

                if (found)
                {
                    t.LoadActions();
                }
            }
        }

19 View Source File : FsmUtil.cs
License : GNU General Public License v3.0
Project Creator : a2659802

public static void ReplaceStringVariable(PlayMakerFSM fsm, string state, string src, string dst)
        {
            Log("Replacing FSM Strings");
            foreach (FsmState t in fsm.FsmStates)
            {
                bool found = false;
                if (t.Name != state && state != "") continue;
                Log($"Found FsmState with name \"{t.Name}\" ");
                foreach (FsmString str in (List<FsmString>) FsmStringParamsField.GetValue(t.ActionData))
                {
                    List<FsmString> val = new List<FsmString>();
                    Log($"Found FsmString with value \"{str}\" ");
                    if (str.Value.Contains(src))
                    {
                        val.Add(dst);
                        found = true;
                        Log($"Found FsmString with value \"{str}\", changing to \"{dst}\" ");
                    }
                    else
                    {
                        val.Add(str);
                    }

                    if (val.Count > 0)
                    {
                        FsmStringParamsField.SetValue(t.ActionData, val);
                    }
                }

                if (found)
                {
                    t.LoadActions();
                }
            }
        }

19 View Source File : PowerToolsIntegration.cs
License : Apache License 2.0
Project Creator : A7ocin

private static void SetAvatarDestroyParent(UMADynamicAvatar avatar, bool destroyParent)
		{
			var umaEditorAvatarType = GetUMAEditorAvatarType();
			var umaEditorAvatar = avatar.GetComponentInChildren(umaEditorAvatarType);
			umaEditorAvatarType.GetField("destroyParent").SetValue(umaEditorAvatar, destroyParent);
		}

19 View Source File : UMAUtils.cs
License : Apache License 2.0
Project Creator : A7ocin

public static void SetActiveSize<TElement>(this List<TElement> list, int size)
		{
			// Check if the FieldInfo is already in the cache
			var listType = typeof(List<TElement>);
			FieldInfo fieldInfo;
			if (itemsFields.TryGetValue(listType, out fieldInfo) == false)
			{
				// Generate the FieldInfo and add it to the cache
				fieldInfo = listType.GetField(FieldName, GetFieldFlags);
				itemsFields.Add(listType, fieldInfo);
			}

			// Set the active size of the given List
			int newSize = size;
			if (newSize < 0) newSize = 0;
			if (newSize > list.Capacity) newSize = list.Capacity;

			fieldInfo.SetValue(list, newSize);
		}

19 View Source File : ThingTrade.cs
License : Apache License 2.0
Project Creator : AantCoder

public override Thing CreateThing(bool useOriginalID = false, int stackCount = 0, bool needPirate = false)
        {
            //useOriginalID не используется.

            var def = (ThingDef)GenDefDatabase.GetDef(typeof(ThingDef), DefName);
            var stuffDef = !string.IsNullOrEmpty(StuffName) ? (ThingDef)GenDefDatabase.GetDef(typeof(ThingDef), StuffName) : null;
            Thing thing = !string.IsNullOrEmpty(StuffName)
                ? ThingMaker.MakeThing(def, stuffDef)
                : ThingMaker.MakeThing(def);
            thing.stackCount = stackCount > 0 ? stackCount : Count;

            if (HitPoints > 0) thing.HitPoints = HitPoints;

            SetFaction(thing, isColonist && !needPirate);

            CompQuality compQuality = thing.TryGetComp<CompQuality>();
            if (compQuality != null)
            {
                compQuality.SetQuality((QualityCategory)Quality, ArtGenerationContext.Outsider);
            }

            if (WornByCorpse)
            {
                Apparel thingA = thing as Apparel;
                if (thingA != null)
                {
                    typeof(Apparel)
                       .GetField("wornByCorpseInt", BindingFlags.Instance | BindingFlags.NonPublic)
                       .SetValue(thingA, true);
                }
            }

            thing.Rotation = new Rot4(Rotation);

            Plant thingP = thing as Plant;
            if (thingP != null) thingP.Growth = Growth;

            thing.Position = Position.Get();

            return thing;
        }

19 View Source File : GameUtils.cs
License : Apache License 2.0
Project Creator : AantCoder

public static void SetWriter(this ScribeSaver scribeSaver, XmlWriter writer)
        {
            FieldInfo fieldInfo = typeof(ScribeSaver).GetField("writer", BindingFlags.Instance | BindingFlags.NonPublic);
            fieldInfo.SetValue(scribeSaver, writer);
        }

19 View Source File : InspectorGenericFields.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

public static void LoadSettings(T target, List<InspectorPropertySetting> settings)
        {
            Type myType = target.GetType();

            List<PropertyInfo> propInfoList = new List<PropertyInfo>(myType.GetProperties());
            for (int i = 0; i < propInfoList.Count; i++)
            {
                PropertyInfo propInfo = propInfoList[i];
                var attrs = (InspectorField[])propInfo.GetCustomAttributes(typeof(InspectorField), false);
                foreach (var attr in attrs)
                {
                    object value = InspectorField.GetSettingValue(settings, propInfo.Name);
                    if (value != null)
                    {
                        propInfo.SetValue(target, value);
                    }
                }
            }

            List<FieldInfo> fieldInfoList = new List<FieldInfo>(myType.GetFields());
            for (int i = 0; i < fieldInfoList.Count; i++)
            {
                FieldInfo fieldInfo = fieldInfoList[i];
                var attrs = (InspectorField[])fieldInfo.GetCustomAttributes(typeof(InspectorField), false);
                foreach (var attr in attrs)
                {
                    object value = InspectorField.GetSettingValue(settings, fieldInfo.Name);
                    if (value != null)
                    {
                        fieldInfo.SetValue(target, value);
                    }
                }
            }
        }

19 View Source File : AddRTTUtility.cs
License : MIT License
Project Creator : absurd-joy

public static void SetPrivateVariable(System.Type t, string varName, object varValue, object objInstance)
        {
            BindingFlags eFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
            FieldInfo fieldInfo = t.GetField(varName, eFlags);
            if (fieldInfo != null)
            {
                fieldInfo.SetValue(objInstance, varValue);
            }
            else
            {
                Debug.LogError("Property `"+varName+"` not found");
            }
        }

19 View Source File : LootSwap.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

private static void UpdateTable(FieldInfo field, object newTable)
        {
            //Console.WriteLine($"Updating {field.Name}");

            field.SetValue(null, newTable);
        }

19 View Source File : TypeExtensionMethods.cs
License : MIT License
Project Creator : actions

public static void SetMemberValue(this Type type, string name, object obj, object value)
        {
            PropertyInfo propertyInfo = GetPublicInstancePropertyInfo(type, name);
            if (propertyInfo != null)
            {
                if (!propertyInfo.SetMethod.IsPublic)
                {
                    // this is here to match original behaviour before we switched to PCL version of code.
                    throw new ArgumentException("Property set method not public.");
                }
                propertyInfo.SetValue(obj, value);
            }
            else
            {
                FieldInfo fieldInfo = GetPublicInstanceFieldInfo(type, name);
                if (fieldInfo != null)
                {
                    fieldInfo.SetValue(obj, value);
                }
            }
        }

19 View Source File : WrappedException.cs
License : MIT License
Project Creator : actions

public Exception Unwrap(IDictionary<String, Type> typeMapping)
        {
            Exception innerException = null;
            if (InnerException != null)
            {
                innerException = InnerException.Unwrap(typeMapping);
                UnwrappedInnerException = innerException;
            }

            Exception exception = null;

            // if they have bothered to map type, use that first.
            if (!String.IsNullOrEmpty(TypeKey))
            {
                Type type;
                if (typeMapping != null && typeMapping.TryGetValue(TypeKey, out type) ||
                    baseTranslatedExceptions.TryGetValue(TypeKey, out type))
                {
                    try
                    {
                        this.Type = type;
                        exception = Activator.CreateInstance(this.Type, Message, innerException) as Exception;
                    }
                    catch (Exception)
                    {
                        // do nothing
                    }
                }
            }

            if (exception == null)
            {
                //no standard mapping, fallback to 
                exception = UnWrap(innerException);
            }

            if (exception is VssException)
            {
                ((VssException)exception).EventId = this.EventId;
                ((VssException)exception).ErrorCode = this.ErrorCode;
            }

            if (exception == null && !String.IsNullOrEmpty(Message))
            {
                // NOTE: We can get exceptions that we can't create, IE. SqlException, AzureExceptions.
                // This is not a failure, we will just wrap the exception in a VssServiceException
                // since the type is not available.
                exception = new VssServiceException(Message, innerException);
            }

            if (exception == null && !string.IsNullOrEmpty(TypeName))
            {
                Debug.replacedert(false, string.Format("Server exception cannot be resolved. Type name: {0}", TypeName));
            }

            if (exception != null
                && !string.IsNullOrEmpty(HelpLink))
            {
                exception.HelpLink = HelpLink;
            }

            if (exception != null
                && !string.IsNullOrEmpty(this.StackTrace))
            {
                FieldInfo stackTraceField = typeof(Exception).GetTypeInfo().GetDeclaredField("_stackTraceString");
                if (stackTraceField != null && !stackTraceField.Attributes.HasFlag(FieldAttributes.Public) && !stackTraceField.Attributes.HasFlag(FieldAttributes.Static))
                {
                    stackTraceField.SetValue(exception, this.StackTrace);
                }
            }

            if (exception != null && exception.GetType() == this.Type)
            {
                TryUnWrapCustomProperties(exception);
            }

            return exception;
        }

19 View Source File : HookInterceptor.cs
License : MIT License
Project Creator : AdamCarballo

private static void OnFormatted(List<string> data) {
			var filteredMethods = HookAttributesParser.HookAttributes.ToArray();
			object param = null;
			for (int i = 0; i < data.Count; i++) {
				if (data[i].StartsWith(UrlParam)) {
					param = data[i].Replace(UrlParam, string.Empty);
				} else {
					filteredMethods = filteredMethods.Where(x => x.Key.Length > i && x.Key[i] == data[i]).ToArray();
					LogVerbose(string.Format("Number of attributes found in {0} group: {1}", data[i], filteredMethods.Length));
				}
			}

			for (int i = 0; i < filteredMethods.Length; i++) {
				LogVerbose("Reflection calling: " + filteredMethods[i].Value.Value.Name);

				var attributeType = filteredMethods[i].Value.Value.GetCustomAttribute(typeof(HookAttribute));
				if (attributeType is HookField) {
					if (param == null) return;
					
					var info = filteredMethods[i].Value.Value as FieldInfo;
					var parsedParam = GetParsedParameter(info.FieldType, param);

					info.SetValue(filteredMethods[i].Value.Key, parsedParam);
				} else if (attributeType is HookProperty) {
					if (param == null) return;

					var info = filteredMethods[i].Value.Value as PropertyInfo;
					var parsedParam = GetParsedParameter(info.PropertyType, param);

					info.SetValue(filteredMethods[i].Value.Key, parsedParam);
				} else if (attributeType is HookMethod) {
					var info = filteredMethods[i].Value.Value as MethodInfo;
					
					// Check if method has parameters
					var parameters = info.GetParameters();

					if (parameters.Length <= 0) {
						info.Invoke(filteredMethods[i].Value.Key, null);
					} else {
						var parsedParam = GetParsedParameter(parameters[0].ParameterType, param);
						info.Invoke(filteredMethods[i].Value.Key, new[] {parsedParam});
					}
				}
			}
		}

19 View Source File : ErrorNotifierModule.cs
License : MIT License
Project Creator : Adoxio

private static string GetTraceByReflection(TraceContext trace)
		{
			// temporarily enable PageOutput (via the _isEnabled field) so that calling Render produces output

			var isEnabledField = typeof(TraceContext).GetField("_isEnabled", BindingFlags.NonPublic | BindingFlags.Instance);
			var originalIsEnabledValue = isEnabledField.GetValue(trace);

			trace.IsEnabled = true;

			try
			{
				var sb = new StringBuilder();

				using (var htw = new Html32TextWriter(new StringWriter(sb, CultureInfo.InvariantCulture)))
				{
					typeof(TraceContext)
						.GetMethod("Render", BindingFlags.NonPublic | BindingFlags.Instance)
						.Invoke(trace, new object[] { htw });
				}

				return sb.ToString();
			}
			finally
			{
				// reset the _isEnabled field

				isEnabledField.SetValue(trace, originalIsEnabledValue);
			}
		}

19 View Source File : GenericExtensions.cs
License : MIT License
Project Creator : adrenak

public static T GetCopyOf<T>(this Component comp, T other) where T : Component {
            Type type = comp.GetType();
            if (type != other.GetType()) return null; // type mis-match
            BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Default | BindingFlags.DeclaredOnly;
            PropertyInfo[] pinfos = type.GetProperties(flags);
            foreach (var pinfo in pinfos) {
                if (pinfo.CanWrite) {
                    try {
                        pinfo.SetValue(comp, pinfo.GetValue(other, null), null);
                    }
                    catch { } // In case of NotImplementedException being thrown. For some reason specifying that exception didn't seem to catch it, so I didn't catch anything specific.
                }
            }
            FieldInfo[] finfos = type.GetFields(flags);
            foreach (var finfo in finfos)
                finfo.SetValue(comp, finfo.GetValue(other));
            return comp as T;
        }

19 View Source File : ModEntry.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn

public void LoadAdvancedMeleeWeapons()
        {
            advancedMeleeWeapons.Clear();
            advancedMeleeWeaponsByType[1].Clear();
            advancedMeleeWeaponsByType[2].Clear();
            advancedMeleeWeaponsByType[3].Clear();
            foreach (IContentPack contentPack in Helper.ContentPacks.GetOwned())
            {
                Monitor.Log($"Reading content pack: {contentPack.Manifest.Name} {contentPack.Manifest.Version} from {contentPack.DirectoryPath}", LogLevel.Debug);
                try
                {
                    AdvancedMeleeWeaponData json = contentPack.ReadJsonFile<AdvancedMeleeWeaponData>("content.json") ?? null;
                    WeaponPackConfigData config = contentPack.ReadJsonFile<WeaponPackConfigData>("config.json") ?? new WeaponPackConfigData();

                    if (json != null)
                    {
                        if (json.weapons != null && json.weapons.Count > 0)
                        {
                            foreach (AdvancedMeleeWeapon weapon in json.weapons)
                            {
                                foreach(KeyValuePair<string, string> kvp in weapon.config)
                                {
                                    FieldInfo fi = weapon.GetType().GetField(kvp.Key);

                                    if(fi == null)
                                    {
                                        Monitor.Log($"Error getting field {kvp.Key} in AdvancedMeleeWeapon clreplaced.", LogLevel.Error);
                                        continue;
                                    }

                                    if (config.variables.ContainsKey(kvp.Value))
                                    {
                                        var val = config.variables[kvp.Value];
                                        if (val.GetType() == typeof(Int64))
                                            fi.SetValue(weapon, Convert.ToInt32(config.variables[kvp.Value]));
                                        else
                                            fi.SetValue(weapon, config.variables[kvp.Value]);
                                    }
                                    else
                                    {
                                        config.variables.Add(kvp.Value, fi.GetValue(weapon));
                                    }
                                }
                                foreach(MeleeActionFrame frame in weapon.frames)
                                {
                                    foreach (KeyValuePair<string, string> kvp in frame.config)
                                    {
                                        FieldInfo fi = frame.GetType().GetField(kvp.Key);

                                        if (fi == null)
                                        {
                                            Monitor.Log($"Error getting field {kvp.Key} in MeleeActionFrame clreplaced.", LogLevel.Error);
                                            continue;
                                        }

                                        if (config.variables.ContainsKey(kvp.Value))
                                        {
                                            fi.SetValue(frame, config.variables[kvp.Value]);
                                        }
                                        else
                                        {
                                            config.variables.Add(kvp.Value, fi.GetValue(frame));
                                        }
                                    }
                                    foreach (AdvancedWeaponProjectile entry in frame.projectiles)
                                    {
                                        foreach (KeyValuePair<string, string> kvp in entry.config)
                                        {
                                            FieldInfo fi = entry.GetType().GetField(kvp.Key);

                                            if (fi == null)
                                            {
                                                Monitor.Log($"Error getting field {kvp.Key} in AdvancedWeaponProjectile clreplaced.", LogLevel.Error);
                                                continue;
                                            }

                                            if (config.variables.ContainsKey(kvp.Value))
                                            {
                                                fi.SetValue(entry, config.variables[kvp.Value]);
                                            }
                                            else
                                            {
                                                config.variables.Add(kvp.Value, fi.GetValue(entry));
                                            }
                                        }
                                    }
                                    if(frame.special != null)
                                    {
                                        foreach (KeyValuePair<string, string> kvp in frame.special.config)
                                        {
                                            if (!frame.special.parameters.ContainsKey(kvp.Key))
                                            {
                                                Monitor.Log($"Error getting key {kvp.Key} in SpecialEffects.parameters", LogLevel.Error);
                                                continue;
                                            }
                                            if (config.variables.ContainsKey(kvp.Value))
                                            {
                                                frame.special.parameters[kvp.Key] = config.variables[kvp.Value].ToString();
                                            }
                                            else
                                            {
                                                config.variables.Add(kvp.Value, frame.special.parameters[kvp.Key]);
                                            }

                                        }
                                    }
                                }
                                foreach (AdvancedEnchantmentData entry in weapon.enchantments)
                                {
                                    int count = 0;
                                    foreach (KeyValuePair<string, string> kvp in entry.config)
                                    {
                                        if (!entry.parameters.ContainsKey(kvp.Key))
                                        {
                                            Monitor.Log($"Error getting key {kvp.Key} in AdvancedEnchantmentData.parameters", LogLevel.Error);
                                            continue;
                                        }

                                        if (config.variables.ContainsKey(kvp.Value))
                                        {
                                            entry.parameters[kvp.Key]  = config.variables[kvp.Value].ToString();
                                        }
                                        else
                                        {
                                            config.variables.Add(kvp.Value, entry.parameters[kvp.Key]);
                                        }
                                    }
                                    advancedEnchantments[entry.name] = entry;
                                    count++;
                                }
                                if (config.variables.Any())
                                {
                                    contentPack.WriteJsonFile("config.json", config);
                                }


                                if (weapon.type == 0)
                                {
                                    Monitor.Log($"Adding specific weapon {weapon.id}");
                                    if (!int.TryParse(weapon.id, out int id))
                                    {
                                        Monitor.Log($"Got name instead of id {weapon.id}");
                                        try
                                        {
                                            id = Helper.Content.Load<Dictionary<int, string>>("Data/weapons", ContentSource.GameContent).First(p => p.Value.StartsWith($"{weapon.id}/")).Key;
                                            Monitor.Log($"Got name-based id {id}");
                                        }
                                        catch (Exception ex)
                                        {
                                            if (mJsonreplacedets != null)
                                            {
                                                id = mJsonreplacedets.GetWeaponId(weapon.id);
                                                if(id == -1)
                                                {
                                                    Monitor.Log($"error getting JSON replacedets weapon {weapon.id}\n{ex}", LogLevel.Error);
                                                    continue;
                                                }
                                                Monitor.Log($"Added JA weapon {weapon.id}, id {id}");
                                            }
                                            else
                                            {
                                                Monitor.Log($"error getting weapon {weapon.id}\n{ex}", LogLevel.Error);
                                                continue;
                                            }
                                        }
                                        
                                    }
                                    if (!advancedMeleeWeapons.ContainsKey(id))
                                        advancedMeleeWeapons[id] = new List<AdvancedMeleeWeapon>();
                                    advancedMeleeWeapons[id].Add(weapon);
                                }
                                else
                                {
                                    advancedMeleeWeaponsByType[weapon.type].Add(weapon);
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Monitor.Log($"error reading content.json file in content pack {contentPack.Manifest.Name}.\r\n{ex}", LogLevel.Error);
                }
            }
            Monitor.Log($"Total advanced melee weapons: {advancedMeleeWeapons.Count}", LogLevel.Debug);
            Monitor.Log($"Total advanced melee dagger attacks: {advancedMeleeWeaponsByType[1].Count}", LogLevel.Debug);
            Monitor.Log($"Total advanced melee club attacks: {advancedMeleeWeaponsByType[2].Count}", LogLevel.Debug);
            Monitor.Log($"Total advanced melee sword attacks: {advancedMeleeWeaponsByType[3].Count}", LogLevel.Debug);
        }

19 View Source File : SquidKidBoss.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn

public override void behaviorAtGameTick(GameTime time)
        {
            typeof(SquidKidBoss).BaseType.GetField("lastFireball", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(this as SquidKid,1000f);
            base.behaviorAtGameTick(time);
            if (Health <= 0)
            {
                return;
            }

            if (this.withinPlayerThreshold(20))
            {
                this.lastIceBall = Math.Max(0f, this.lastIceBall - (float)time.ElapsedGameTime.Milliseconds);
                this.lastLightning = Math.Max(0f, this.lastLightning - (float)time.ElapsedGameTime.Milliseconds);

                if (!startedLightning && lastLightning < (ModEntry.IsLessThanHalfHealth(this) ? 500f : 1000f))
                {
                    startedLightning = true;

                    List<Farmer> farmers = new List<Farmer>();
                    FarmerCollection.Enumerator enumerator = currentLocation.farmers.GetEnumerator();
                    while (enumerator.MoveNext())
                    {
                        farmers.Add(enumerator.Current);
                    }
                    playerPosition = farmers[Game1.random.Next(0, farmers.Count)].position;

                    Microsoft.Xna.Framework.Rectangle lightningSourceRect = new Rectangle(0, 0, 16, 16);
                    float markerScale = 8f;
                    Vector2 drawPosition = playerPosition + new Vector2(-16*markerScale/2 + 32f,-16*markerScale/ 2 + 32f);

                    Game1.currentLocation.temporarySprites.Add(new TemporaryAnimatedSprite("TileSheets\\Projectiles", lightningSourceRect, 9999f, 1, 999, drawPosition, false, Game1.random.NextDouble() < 0.5, (playerPosition.Y + 32f) / 10000f + 0.001f, 0.025f, Color.White, markerScale, 0f, 0f, 0f, false)
                    {
                        light = true,
                        lightRadius = 2f,
                        delayBeforeAnimationStart = 200,
                        lightcolor = Color.Black
                    });
                }

                if (lastLightning == 0f)
                {
                    startedLightning = false;
                    lightningStrike(playerPosition);
                    lastLightning = Game1.random.Next(1000, 2000) * (ModEntry.IsLessThanHalfHealth(this) ? 1 : 2);
                }
                if (lastIceBall == 0f)
                {
                    Vector2 trajectory = ModEntry.VectorFromDegree(Game1.random.Next(0,360)) * 10f;
                    currentLocation.projectiles.Add(new BossProjectile((int)Math.Round(20 * difficulty), 9, 3, 4, 0f, trajectory.X, trajectory.Y, getStandingPosition(), "", "", true, false, currentLocation, this, false, null, 19));

                    projectileCount++;

                    if (projectileCount >= (ModEntry.IsLessThanHalfHealth(this) ? 8 : 4))
                    {
                        projectileCount = 0;
                        lastIceBall = Game1.random.Next(1200, 3500);
                    }
                    else
                    {
                        lastIceBall = 100;
                    }
                    if (lastIceBall != 0f && Game1.random.NextDouble() < 0.05)
                    {
                        Halt();
                        setTrajectory((int)Utility.getVelocityTowardPlayer(Utility.Vector2ToPoint(base.getStandingPosition()), 8f, base.Player).X, (int)(-(int)Utility.getVelocityTowardPlayer(Utility.Vector2ToPoint(base.getStandingPosition()), 8f, base.Player).Y));
                    }
                }

            }
        }

19 View Source File : MobileTV.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn

public override void draw(SpriteBatch spriteBatch, int x, int y, float alpha = 1)
        {
            SetScreenScale();
            TemporaryAnimatedSprite sprite = (TemporaryAnimatedSprite)typeof(TV).GetField("screen", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(this);
            if(sprite != null)
            {
                spriteBatch.Draw(backgroundTexture, ModEntry.api.GetScreenRectangle(), Color.White);
                sprite.scale = GetScale(sprite.sourceRect);
                typeof(TV).GetField("screen", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(this, sprite);
                sprite.update(Game1.currentGameTime);
                sprite.draw(spriteBatch, true, 0, 0, 1f);
                TemporaryAnimatedSprite  sprite2 = (TemporaryAnimatedSprite)typeof(TV).GetField("screenOverlay", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(this);
                if (sprite2 != null)
                {
                    sprite2.scale = GetScale(sprite2.sourceRect);
                    typeof(TV).GetField("screenOverlay", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(this, sprite2);
                    sprite2.update(Game1.currentGameTime);
                    sprite2.draw(spriteBatch, true, 0, 0, 1f);
                }
            }
        }

19 View Source File : SDatePatches.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn

private static void SDate_Postfix(SDate __instance)
        {
            typeof(SDate).GetField("DaysInSeason", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(__instance, Config.DaysPerMonth);
        }

19 View Source File : SwimHelperEvents.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn

public static void AbigailCaveTick()
        {

            Game1.player.CurrentToolIndex = Game1.player.items.Count;

            List<NPC> list = Game1.player.currentLocation.characters.ToList().FindAll((n) => (n is Monster) && (n as Monster).Health <= 0);
            foreach(NPC n in list)
            {
                Game1.player.currentLocation.characters.Remove(n);
            }

            if (abigailTicks.Value < 0)
            {
                return;
            }
            Game1.exitActiveMenu();

            if (abigailTicks.Value == 0)
            {
                FieldInfo f1 = Game1.player.currentLocation.characters.GetType().GetField("OnValueRemoved", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);
                f1.SetValue(Game1.player.currentLocation.characters, null);
            }

            Vector2 v = Vector2.Zero;
            float yrt = (float)(1/Math.Sqrt(2));
            if (Helper.Input.IsDown(SButton.Up) || Helper.Input.IsDown(SButton.RightThumbstickUp))
            {
                if(Helper.Input.IsDown(SButton.Right) || Helper.Input.IsDown(SButton.RightThumbstickRight))
                    v = new Vector2(yrt, -yrt);
                else if(Helper.Input.IsDown(SButton.Left) || Helper.Input.IsDown(SButton.RightThumbstickLeft))
                    v = new Vector2(-yrt, -yrt);
                else 
                    v = new Vector2(0, -1);
            }
            else if (Helper.Input.IsDown(SButton.Down) || Helper.Input.IsDown(SButton.RightThumbstickDown))
            {
                if(Helper.Input.IsDown(SButton.Right) || Helper.Input.IsDown(SButton.RightThumbstickRight))
                    v = new Vector2(yrt, yrt);
                else if(Helper.Input.IsDown(SButton.Left) || Helper.Input.IsDown(SButton.RightThumbstickLeft))
                    v = new Vector2(-yrt, yrt);
                else 
                    v = new Vector2(0, 1);
            }
            else if (Helper.Input.IsDown(SButton.Right) || Helper.Input.IsDown(SButton.RightThumbstickDown))
                v = new Vector2(1, 0);
            else if (Helper.Input.IsDown(SButton.Left) || Helper.Input.IsDown(SButton.RightThumbstickLeft))
                v = new Vector2(-1, 0);
            else if (Helper.Input.IsDown(SButton.MouseLeft))
            {
                float x = Game1.viewport.X + Game1.getOldMouseX() - Game1.player.position.X;
                float y = Game1.viewport.Y + Game1.getOldMouseY() - Game1.player.position.Y;
                float dx = Math.Abs(x);
                float dy = Math.Abs(y);
                if(y < 0)
                {
                    if(x > 0)
                    {
                        if(dy > dx)
                        {
                            if (dy-dx > dy / 2)
                                v = new Vector2(0, -1);
                            else
                                v = new Vector2(yrt, -yrt);

                        }
                        else
                        {
                            if (dx - dy > x / 2)
                                v = new Vector2(1, 0);
                            else
                                v = new Vector2(yrt, -yrt);
                        }
                    }
                    else
                    {
                        if (dy > dx)
                        {
                            if (dy - dx > dy / 2)
                                v = new Vector2(0, -1);
                            else
                                v = new Vector2(-yrt, -yrt);

                        }
                        else
                        {
                            if (dx - dy > x / 2)
                                v = new Vector2(-1, 0);
                            else
                                v = new Vector2(-yrt, -yrt);
                        }
                    }
                }
                else
                {
                    if (x > 0)
                    {
                        if (dy > dx)
                        {
                            if (dy - dx > dy / 2)
                                v = new Vector2(0, 1);
                            else
                                v = new Vector2(yrt, yrt);

                        }
                        else
                        {
                            if (dx - dy > x / 2)
                                v = new Vector2(1, 0);
                            else
                                v = new Vector2(yrt, yrt);
                        }
                    }
                    else
                    {
                        if (dy > dx)
                        {
                            if (dy - dx > dy / 2)
                                v = new Vector2(0, -1);
                            else
                                v = new Vector2(-yrt, yrt);

                        }
                        else
                        {
                            if (dx - dy > x / 2)
                                v = new Vector2(-1, 0);
                            else
                                v = new Vector2(-yrt, yrt);
                        }
                    }
                }
            }

            if (v != Vector2.Zero && Game1.player.millisecondsPlayed - lastProjectile.Value > 350)
            {
                Game1.player.currentLocation.projectiles.Add(new AbigailProjectile(1, 383, 0, 0, 0, v.X * 6, v.Y * 6, new Vector2(Game1.player.getStandingX() - 24, Game1.player.getStandingY() - 48), "Cowboy_monsterDie", "Cowboy_gunshot", false, true, Game1.player.currentLocation, Game1.player, true)); 
                lastProjectile.Value = Game1.player.millisecondsPlayed;
            }

            foreach (SButton button in abigailShootButtons)
            {
                if (Helper.Input.IsDown(button))
                {
                    switch (button)
                    {
                        case SButton.Up:
                            break;
                        case SButton.Right:
                            v = new Vector2(1, 0);
                            break;
                        case SButton.Down:
                            v = new Vector2(0, 1);
                            break;
                        default:
                            v = new Vector2(-1, 0);
                            break;
                    }
                }
            }


            abigailTicks.Value++;
            if(abigailTicks.Value > 80000 / 16f)
            {
                if (Game1.player.currentLocation.characters.ToList().FindAll((n) => (n is Monster)).Count > 0)
                    return;

                abigailTicks.Value = -1;
                Game1.player.hat.Value = null;
                Game1.stopMusicTrack(Game1.MusicContext.Default);

                if(!Game1.player.mailReceived.Contains("ScubaFins"))
                {
                    Game1.playSound("Cowboy_Secret");
                    SwimMaps.AddScubaChest(Game1.player.currentLocation, new Vector2(8, 8), "ScubaFins");
                }

                Game1.player.currentLocation.setMapTile(8, 16, 91, "Buildings", null);
                Game1.player.currentLocation.setMapTile(9, 16, 92, "Buildings", null);
                Game1.player.currentLocation.setTileProperty(9, 16, "Back", "Water", "T");
                Game1.player.currentLocation.setMapTile(10, 16, 93, "Buildings", null);
                Game1.player.currentLocation.setMapTile(8, 17, 107, "Buildings", null);
                Game1.player.currentLocation.setMapTile(9, 17, 108, "Back", null);
                Game1.player.currentLocation.setTileProperty(9, 17, "Back", "Water", "T");
                Game1.player.currentLocation.removeTile(9, 17, "Buildings");
                Game1.player.currentLocation.setMapTile(10, 17, 109, "Buildings", null); 
                Game1.player.currentLocation.setMapTile(8, 18, 139, "Buildings", null);
                Game1.player.currentLocation.setMapTile(9, 18, 140, "Buildings", null);
                Game1.player.currentLocation.setMapTile(10, 18, 141, "Buildings", null);
                SwimMaps.AddWaterTiles(Game1.player.currentLocation);
            }
            else
            {
                if (Game1.random.NextDouble() < 0.03)
                {
                    int which = Game1.random.Next(3);
                    Point p = new Point();
                    switch (Game1.random.Next(4))
                    {
                        case 0:
                            p = new Point(8 + which, 1);
                            break;
                        case 1:
                            p = new Point(1, 8 + which);
                            break;
                        case 2:
                            p = new Point(8 + which, 16);
                            break;
                        case 3:
                            p = new Point(16, 8 + which);
                            break;
                    }
                    Game1.player.currentLocation.characters.Add(new AbigailMetalHead(new Vector2(p.X * Game1.tileSize, p.Y * Game1.tileSize), 0));
                }

            }
        }

19 View Source File : ModEntry.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn

private void UpdateTicked(object sender, UpdateTickedEventArgs e)
        {
            if (!Context.IsWorldReady)
                return;
            if (drivingOff && !droveOff)
            {
                FieldInfo pos = typeof(BusStop).GetField("busPosition", BindingFlags.NonPublic | BindingFlags.Instance);
                BusStop bs = (BusStop)Game1.getLocationFromName("BusStop");
                if (((Vector2)pos.GetValue(bs)).X + 512f >= 0f)
                {
                    FieldInfo mot = typeof(BusStop).GetField("busMotion", BindingFlags.NonPublic | BindingFlags.Instance);
                    mot.SetValue(bs, new Vector2(((Vector2)mot.GetValue(bs)).X - 0.075f, ((Vector2)mot.GetValue(bs)).Y));
                }
                else
                {
                    droveOff = true;
                    drivingOff = false;
                }
            }
        }

19 View Source File : ModEntry.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn

private void OneSecondUpdateTicked(object sender, OneSecondUpdateTickedEventArgs e)
        {
            if (Game1.timeOfDay >= Config.LeaveTime && !droveOff && !drivingOff)
            {
                int gone = 0;
                foreach (NPC npc in Game1.getLocationFromName("BusStop").characters)
                {
                    if (npc.getTileLocation().X > 1000 && npc.getTileLocation().Y > 1000)
                    {
                        gone++;
                    }
                    if (npc.getTileLocation().X == 12 && npc.getTileLocation().Y == 9)
                    {
                        foreach (RNPC rnpc in RNPCs)
                        {
                            if (npc.name.Equals(rnpc.nameID))
                            {
                                Game1.warpCharacter(npc, "BusStop", new Vector2(10000, 10000));
                            }
                        }
                    }
                }

                if (!drivingOff && gone == RNPCs.Count)
                {
                    //Alert("Driving off");
                    drivingOff = true;
                    FieldInfo door = typeof(BusStop).GetField("busDoor", BindingFlags.NonPublic | BindingFlags.Instance);
                    FieldInfo pos = typeof(BusStop).GetField("busPosition", BindingFlags.NonPublic | BindingFlags.Instance);
                    FieldInfo mot = typeof(BusStop).GetField("busMotion", BindingFlags.NonPublic | BindingFlags.Instance);
                    BusStop bs = (BusStop)Game1.getLocationFromName("BusStop");
                    door.SetValue(bs, new TemporaryAnimatedSprite("LooseSprites\\Cursors", new Microsoft.Xna.Framework.Rectangle(288, 1311, 16, 38), (Vector2)pos.GetValue(bs) + new Vector2(16f, 26f) * 4f, false, 0f, Color.White)
                    {
                        interval = 999999f,
                        animationLength = 6,
                        holdLastFrame = true,
                        layerDepth = (((Vector2)pos.GetValue(bs)).Y + 192f) / 10000f + 1E-05f,
                        scale = 4f
                    });
                    ((TemporaryAnimatedSprite)door.GetValue(bs)).timer = 0f;
                    ((TemporaryAnimatedSprite)door.GetValue(bs)).interval = 70f;
                    ((TemporaryAnimatedSprite)door.GetValue(bs)).endFunction = new TemporaryAnimatedSprite.endBehavior(delegate
                    {
                        bs.localSound("batFlap");
                        bs.localSound("busDriveOff");
                    });
                    bs.localSound("trashcanlid");
                    ((TemporaryAnimatedSprite)door.GetValue(bs)).paused = false;

                    for (int i = 11; i < 19; i++)
                    {
                        for (int j = 7; j < 10; j++)
                        {
                            if (i == 12 && j == 9)
                                continue;
                            bs.removeTile(i, j, "Buildings");
                            //bs.setTileProperty(i, j, "Buildings", "Preplacedable", "T");
                        }
                    }

                }
            }
        }

19 View Source File : ModEntry.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn

private void UpdateTicking(object sender, UpdateTickingEventArgs e)
        {
            if (!Context.IsWorldReady)
                return;
            GameLocation location = Game1.getPlayerOrEventFarmer().currentLocation;
            Netcode.NetCollection<Debris> debris = location.debris;
            GameTime time = new GameTime();
            float rangeMult = magnetRangeMult;
            bool infRange = (rangeMult < 0 ? true : false);
            int speedMult = magnetSpeedMult; 
            bool noBounce = noLootBounce;
            bool noWave = noLootWave;

            for (int j = 0; j < debris.Count; j++)
            {
                Debris d = debris[j];
                NetObjectShrinkList<Chunk> chunks = (NetObjectShrinkList<Chunk>) typeof(Debris).GetField("chunks", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(d);

                if (chunks.Count == 0)
                {
                    continue;
                }
                d.timeSinceDoneBouncing += (float)time.ElapsedGameTime.Milliseconds;
                if (d.timeSinceDoneBouncing >= (d.floppingFish ? 2500f : ((d.debrisType == Debris.DebrisType.SPRITECHUNKS || d.debrisType == Debris.DebrisType.NUMBERS) ? 1800f : (noBounce ? 0f : 600f))))
                {
                    if (d.debrisType == Debris.DebrisType.LETTERS || d.debrisType == Debris.DebrisType.NUMBERS || d.debrisType == Debris.DebrisType.SQUARES || d.debrisType == Debris.DebrisType.SPRITECHUNKS || (d.debrisType == Debris.DebrisType.CHUNKS && chunks[0].debrisType - chunks[0].debrisType % 2 != 8))
                    {
                        continue;
                    }
                    if (d.debrisType == Debris.DebrisType.ARCHAEOLOGY || d.debrisType == Debris.DebrisType.OBJECT || d.debrisType == Debris.DebrisType.RESOURCE || d.debrisType == Debris.DebrisType.CHUNKS)
                    {
                        d.chunksMoveTowardPlayer = true;
                    }
                    d.timeSinceDoneBouncing = 0f;
                }
                if (location.farmers.Count == 0)
                {
                    continue;
                }
                Vector2 total = default(Vector2);
                foreach (Chunk chunk in chunks)
                {
                    total += chunk.position.Value;
                }
                Vector2 position = total / (float)chunks.Count;
                if (d.player.Value != null && (d.player.Value.currentLocation != location || !infRange && !(Math.Abs(position.X + 32f - (float)d.player.Value.getStandingX()) <= (float)d.player.Value.MagneticRadius * rangeMult && Math.Abs(position.Y + 32f - (float)d.player.Value.getStandingY()) <= (float)d.player.Value.MagneticRadius * rangeMult)))
                {
                    d.player.Value = null;
                }
                Farmer farmer = d.player.Value;
                if (farmer == null && (Game1.IsMasterGame || location.isTemp()))
                {
                    float bestDistance = float.MaxValue;
                    Farmer bestFarmer = null;
                    foreach (Farmer f in location.farmers)
                    {
                        bool pir = infRange || (Math.Abs(position.X + 32f - (float)f.getStandingX()) <= (float)f.MagneticRadius * rangeMult && Math.Abs(position.Y + 32f - (float)f.getStandingY()) <= (float)f.MagneticRadius * rangeMult);
                        if ((f.UniqueMultiplayerID != d.DroppedByPlayerID || bestFarmer == null) && pir)
                        {
                            float distance = (f.Position - position).LengthSquared();
                            if (distance < bestDistance || (bestFarmer != null && bestFarmer.UniqueMultiplayerID == d.DroppedByPlayerID))
                            {
                                bestFarmer = f;
                                bestDistance = distance;
                            }
                        }
                    }
                    farmer = bestFarmer;
                }

                bool anyCouldMove = false;
                for (int i = chunks.Count - 1; i >= 0; i--)
                {
                    Chunk chunk = chunks[i];
                    chunk.position.UpdateExtrapolation(chunk.getSpeed());
                    if (chunk.alpha > 0.1f && (d.debrisType == Debris.DebrisType.SPRITECHUNKS || d.debrisType == Debris.DebrisType.NUMBERS) && d.timeSinceDoneBouncing > 600f)
                    {
                        chunk.alpha = (1800f - d.timeSinceDoneBouncing) / 1000f;
                    }
                    if (chunk.position.X < -128f || chunk.position.Y < -64f || chunk.position.X >= (float)(location.map.DisplayWidth + 64) || chunk.position.Y >= (float)(location.map.DisplayHeight + 64))
                    {
                        chunks.RemoveAt(i);
                    }
                    else
                    {
                        bool canMoveTowardPlayer = farmer != null;
                        if (canMoveTowardPlayer)
                        {
                            Debris.DebrisType value = d.debrisType.Value;
                            if (value - Debris.DebrisType.ARCHAEOLOGY > 1)
                            {
                                canMoveTowardPlayer = (value != Debris.DebrisType.RESOURCE || farmer.couldInventoryAcceptThisObject(chunk.debrisType - chunk.debrisType % 2, 1, 0));
                            }
                            else if (d.item != null)
                            {
                                canMoveTowardPlayer = farmer.couldInventoryAcceptThisItem(d.item);
                            }
                            else
                            {
                                if (chunk.debrisType < 0)
                                {
                                    canMoveTowardPlayer = farmer.couldInventoryAcceptThisItem(new StardewValley.Object(Vector2.Zero, chunk.debrisType * -1, false));
                                }
                                else
                                {
                                    canMoveTowardPlayer = farmer.couldInventoryAcceptThisObject(chunk.debrisType, 1, d.itemQuality);
                                }
                                if (chunk.debrisType == 102 && farmer.hasMenuOpen)
                                {
                                    canMoveTowardPlayer = false;
                                }
                            }
                            anyCouldMove = (anyCouldMove || canMoveTowardPlayer);
                            if (canMoveTowardPlayer)
                            {
                                d.player.Value = farmer;
                            }
                        }
                        if ((d.chunksMoveTowardPlayer || d.isFishable) && canMoveTowardPlayer)
                        {
                            if (d.player.Value.IsLocalPlayer)
                            {
                                if(speedMult < 0)
                                {
                                    chunk.position.X = d.player.Value.Position.X;
                                    chunk.position.Y = d.player.Value.Position.Y;
                                } 
                                else
                                {
                                    for (int l = 1; l < speedMult; l++)
                                    {
                                        if (noWave)
                                        {
                                            if (chunk.position.X < d.player.Value.Position.X - 12f)
                                            {
                                                chunk.xVelocity.Value = 8f;
                                            }
                                            else if (chunk.position.X > d.player.Value.Position.X + 12f)
                                            {
                                                chunk.xVelocity.Value = -8f;
                                            }
                                            if (chunk.position.Y < d.player.Value.Position.Y - 12f)
                                            {
                                                chunk.yVelocity.Value = -8f;
                                            }
                                            else if (chunk.position.Y > d.player.Value.Position.Y + 12f)
                                            {
                                                chunk.yVelocity.Value = 8f;
                                            }
                                        }
                                        else {
                                            if (chunk.position.X < d.player.Value.Position.X - 12f)
                                            {
                                                chunk.xVelocity.Value = Math.Min(chunk.xVelocity + 0.8f, 8f);
                                            }
                                            else if (chunk.position.X > d.player.Value.Position.X + 12f)
                                            {
                                                chunk.xVelocity.Value = Math.Max(chunk.xVelocity - 0.8f, -8f);
                                            }
                                            if (chunk.position.Y + 32f < (float)(d.player.Value.getStandingY() - 12))
                                            {
                                                chunk.yVelocity.Value = Math.Max(chunk.yVelocity - 0.8f, -8f);
                                            }
                                            else if (chunk.position.Y + 32f > (float)(d.player.Value.getStandingY() + 12))
                                            {
                                                chunk.yVelocity.Value = Math.Min(chunk.yVelocity + 0.8f, 8f);
                                            }
                                        }
                                        chunk.position.X += chunk.xVelocity;
                                        chunk.position.Y -= chunk.yVelocity;
                                    }
                                }
                            }
                        }
                    }
                }
                typeof(Debris).GetField("chunks", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(d, chunks);
            }
            
        }

19 View Source File : FieldRef.cs
License : GNU General Public License v3.0
Project Creator : Aekras1a

public unsafe void SetValue(DarksVMContext ctx, DarksVMSlot slot, PointerType type)
        {
            if(field.DeclaringType.IsValueType && instance is IReference)
            {
                TypedReference typedRef;
                ((IReference) instance).ToTypedReference(ctx, &typedRef, field.DeclaringType);
                field.SetValueDirect(typedRef, slot.ToObject(field.FieldType));
            }
            else
            {
                field.SetValue(instance, slot.ToObject(field.FieldType));
            }
        }

19 View Source File : Stfld.cs
License : GNU General Public License v3.0
Project Creator : Aekras1a

public unsafe void Load(DarksVMContext ctx, out ExecutionState state)
        {
            var sp = ctx.Registers[DarksVMConstants.REG_SP].U4;
            var fieldSlot = ctx.Stack[sp--];
            var valSlot = ctx.Stack[sp--];
            var objSlot = ctx.Stack[sp--];

            var field = (FieldInfo) ctx.Instance.Data.LookupReference(fieldSlot.U4);
            if(!field.IsStatic && objSlot.O == null)
                throw new NullReferenceException();

            object value;
            if(Type.GetTypeCode(field.FieldType) == TypeCode.String && valSlot.O == null)
                value = ctx.Instance.Data.LookupString(valSlot.U4);
            else
                value = valSlot.ToObject(field.FieldType);

            if(field.DeclaringType.IsValueType && objSlot.O is IReference)
            {
                TypedReference typedRef;
                ((IReference) objSlot.O).ToTypedReference(ctx, &typedRef, field.DeclaringType);
                TypedReferenceHelpers.CastTypedRef(&typedRef, field.DeclaringType);
                field.SetValueDirect(typedRef, value);
            }
            else
            {
                field.SetValue(objSlot.ToObject(field.DeclaringType), value);
            }

            ctx.Stack.SetTopPosition(sp);
            ctx.Registers[DarksVMConstants.REG_SP].U4 = sp;
            state = ExecutionState.Next;
        }

19 View Source File : PhotonPlayer.cs
License : GNU General Public License v3.0
Project Creator : aelariane

internal void InternalChangeLocalID(int newID)
    {
        if (!this.IsLocal)
        {
            Debug.LogError("ERROR You should never change PhotonPlayer IDs!");
            return;
        }
        var info = GetType().GetField(nameof(ID), System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
        if (info != null)
        {
            info.SetValue(this, newID);
            InitializeCounters();
        }
        targetArray[0] = ID;
    }

19 View Source File : SettingsSetterViewController.cs
License : MIT License
Project Creator : Aeroluna

internal void Init(StartStandardLevelParameters startParameters, MenuTransitionsHelper menuTransitionsHelper)
        {
            if (startParameters.DifficultyBeatmap.beatmapData is CustomBeatmapData customBeatmapData)
            {
                Dictionary<string, object?>? settings = customBeatmapData.beatmapCustomData.Get<Dictionary<string, object?>>("_settings");
                if (settings != null)
                {
                    _contents.Clear();
                    _modifiedParameters = startParameters;

                    Dictionary<string, object?>? jsonPlayerOptions = settings.Get<Dictionary<string, object?>>("_playerOptions");
                    if (jsonPlayerOptions != null)
                    {
                        PlayerSpecificSettings playerSettings = startParameters.PlayerSpecificSettings;
                        List<Dictionary<string, object>> settablePlayerSettings = SettingSetterSettableSettingsManager.SettingsTable["_playerOptions"];

                        PlayerSpecificSettings modifiedPlayerSettings = playerSettings.CopyWith();

                        foreach (Dictionary<string, object> settablePlayerSetting in settablePlayerSettings)
                        {
                            string name = (string)settablePlayerSetting["_name"];
                            string fieldName = (string)settablePlayerSetting["_fieldName"];

                            object? json = jsonPlayerOptions.Get<object>(fieldName);
                            if (json != null)
                            {
                                FieldInfo field = typeof(PlayerSpecificSettings).GetField(fieldName, BindingFlags.Instance | BindingFlags.NonPublic);
                                object activeValue = field.GetValue(playerSettings);
                                if (json is string jsonString)
                                {
                                    json = Enum.Parse(typeof(EnvironmentEffectsFilterPreset), jsonString);
                                }
                                else if (json is IConvertible)
                                {
                                    json = Convert.ChangeType(json, activeValue.GetType());
                                }

                                if (!json.Equals(activeValue))
                                {
                                    _contents.Add(new ListObject($"[Player Options] {name}", $"{activeValue} > {json}"));
                                    field.SetValue(modifiedPlayerSettings, json);
                                }
                            }
                        }

                        _modifiedParameters.PlayerSpecificSettings = modifiedPlayerSettings;
                    }

                    Dictionary<string, object?>? jsonModifiers = settings.Get<Dictionary<string, object?>>("_modifiers");
                    if (jsonModifiers != null)
                    {
                        GameplayModifiers gameplayModifiers = startParameters.GameplayModifiers;
                        List<Dictionary<string, object>> settableGameplayModifiers = SettingSetterSettableSettingsManager.SettingsTable["_modifiers"];

                        GameplayModifiers modifiedGameplayModifiers = gameplayModifiers.CopyWith();

                        foreach (Dictionary<string, object> settableGameplayModifier in settableGameplayModifiers)
                        {
                            string name = (string)settableGameplayModifier["_name"];
                            string fieldName = (string)settableGameplayModifier["_fieldName"];

                            object? json = jsonModifiers.Get<object>(fieldName);
                            if (json != null)
                            {
                                FieldInfo field = typeof(GameplayModifiers).GetField(fieldName, BindingFlags.Instance | BindingFlags.NonPublic);
                                object activeValue = field.GetValue(gameplayModifiers);
                                if (json is string jsonString)
                                {
                                    switch (fieldName)
                                    {
                                        case "_energyType":
                                            json = Enum.Parse(typeof(GameplayModifiers.EnergyType), jsonString);
                                            break;

                                        case "_enabledObstacleType":
                                            json = Enum.Parse(typeof(GameplayModifiers.EnabledObstacleType), jsonString);
                                            break;

                                        case "_songSpeed":
                                            json = Enum.Parse(typeof(GameplayModifiers.SongSpeed), jsonString);
                                            break;
                                    }
                                }
                                else if (json is IConvertible)
                                {
                                    json = Convert.ChangeType(json, activeValue.GetType());
                                }

                                if (!json.Equals(activeValue))
                                {
                                    _contents.Add(new ListObject($"[Modifiers] {name}", $"{activeValue} > {json}"));
                                    field.SetValue(modifiedGameplayModifiers, json);
                                }
                            }
                        }

                        _modifiedParameters.GameplayModifiers = modifiedGameplayModifiers;
                    }

                    Dictionary<string, object?>? jsonEnvironments = settings.Get<Dictionary<string, object?>>("_environments");
                    if (jsonEnvironments != null)
                    {
                        OverrideEnvironmentSettings? environmentOverrideSettings = startParameters.OverrideEnvironmentSettings;

                        if (environmentOverrideSettings != null)
                        {
                            Dictionary<string, object> settableEnvironmentSetting = SettingSetterSettableSettingsManager.SettingsTable["_environments"].First();
                            string name = (string)settableEnvironmentSetting["_name"];
                            string fieldName = (string)settableEnvironmentSetting["_fieldName"];
                            bool activeValue = environmentOverrideSettings.overrideEnvironments;
                            bool? json = jsonEnvironments.Get<bool>(fieldName);

                            if (json != null && json != activeValue)
                            {
                                _contents.Add(new ListObject($"[Environments] {name}", $"{activeValue} > {json}"));

                                // copy fields from original overrideenvironmentsettings to our new copy
                                OverrideEnvironmentSettings modifiedOverrideEnvironmentSettings = new OverrideEnvironmentSettings();
                                modifiedOverrideEnvironmentSettings.SetField("_data", environmentOverrideSettings.GetField<Dictionary<EnvironmentTypeSO, EnvironmentInfoSO>, OverrideEnvironmentSettings>("_data"));

                                modifiedOverrideEnvironmentSettings.overrideEnvironments = json.Value;

                                _modifiedParameters.OverrideEnvironmentSettings = modifiedOverrideEnvironmentSettings;
                            }
                        }
                    }

                    Dictionary<string, object?>? jsonColors = settings.Get<Dictionary<string, object?>>("_colors");
                    if (jsonColors != null)
                    {
                        ColorSchemesSettings? colorSchemesSettings = OverrideColorScheme;

                        if (colorSchemesSettings != null)
                        {
                            Dictionary<string, object> settableColorSetting = SettingSetterSettableSettingsManager.SettingsTable["_colors"].First();
                            string name = (string)settableColorSetting["_name"];
                            string fieldName = (string)settableColorSetting["_fieldName"];
                            bool activeValue = colorSchemesSettings.overrideDefaultColors;
                            bool? json = jsonColors.Get<bool>(fieldName);

                            if (json != null && json != activeValue)
                            {
                                _contents.Add(new ListObject($"[Colors] {name}", $"{activeValue} > {json}"));

                                _modifiedParameters.OverrideColorScheme = json.Value ? colorSchemesSettings.GetOverrideColorScheme() : null;
                            }
                        }
                    }

                    _modifiedMainSettings = null;
                    _cachedMainSettings = null;
                    Dictionary<string, object?>? jsonGraphics = settings.Get<Dictionary<string, object?>>("_graphics");
                    if (jsonGraphics != null)
                    {
                        MainSettingsModelSO mainSettingsModel = MainSettings;
                        List<Dictionary<string, object>> settableGraphicsSettings = SettingSetterSettableSettingsManager.SettingsTable["_graphics"];

                        _cachedMainSettings = new SettableMainSettings(
                            mainSettingsModel.mirrorGraphicsSettings,
                            mainSettingsModel.mainEffectGraphicsSettings,
                            mainSettingsModel.smokeGraphicsSettings,
                            mainSettingsModel.burnMarkTrailsEnabled,
                            mainSettingsModel.screenDisplacementEffectsEnabled,
                            mainSettingsModel.maxShockwaveParticles);
                        _modifiedMainSettings = _cachedMainSettings with { };

                        foreach (Dictionary<string, object> settableGraphicSetting in settableGraphicsSettings)
                        {
                            string name = (string)settableGraphicSetting["_name"];
                            string fieldName = (string)settableGraphicSetting["_fieldName"];

                            object? json = jsonGraphics.Get<object>(fieldName);
                            if (json != null)
                            {
                                // substring is to remove underscore
                                object valueSO = typeof(MainSettingsModelSO).GetField(fieldName.Substring(1), BindingFlags.Instance | BindingFlags.Public).GetValue(mainSettingsModel);
                                object activeValue = valueSO switch
                                {
                                    BoolSO boolSO => boolSO.value,
                                    IntSO intSO => intSO.value,
                                    _ => throw new InvalidOperationException($"How the hell did you reach this? [{valueSO.GetType()}]"),
                                };
                                if (json is IConvertible)
                                {
                                    json = Convert.ChangeType(json, activeValue.GetType());
                                }

                                if (!json.Equals(activeValue))
                                {
                                    _contents.Add(new ListObject($"[Graphics] {name}", $"{activeValue} > {json}"));
                                    typeof(SettableMainSettings).GetField(fieldName, BindingFlags.Instance | BindingFlags.NonPublic).SetValue(_modifiedMainSettings, json);
                                }
                            }
                        }
                    }

                    _settableSettingsToSet = null;
                    foreach (KeyValuePair<string, Dictionary<string, ISettableSetting>> groupSettingPair in SettingSetterSettableSettingsManager.SettableSettings)
                    {
                        Dictionary<string, object?>? jsonGroup = settings.Get<Dictionary<string, object?>>(groupSettingPair.Key);
                        if (jsonGroup != null)
                        {
                            _settableSettingsToSet = new List<Tuple<ISettableSetting, object>>();

                            foreach (KeyValuePair<string, ISettableSetting> settableSettingPair in groupSettingPair.Value)
                            {
                                object? json = jsonGroup.Get<object>(settableSettingPair.Key);
                                ISettableSetting settableSetting = settableSettingPair.Value;
                                object activeValue = settableSetting.TrueValue;
                                if (json != null && !json.Equals(activeValue))
                                {
                                    _contents.Add(new ListObject($"[{settableSetting.GroupName}] {settableSetting.FieldName}", $"{activeValue} > {json}"));
                                    _settableSettingsToSet.Add(new Tuple<ISettableSetting, object>(settableSetting, json));
                                }
                            }
                        }
                    }

                    if (_contents.Any())
                    {
                        if (_contentObject != null)
                        {
                            Destroy(_contentObject);
                        }

                        DoPresent = true;
                        _defaultParameters = startParameters;
                        _menuTransitionsHelper = menuTransitionsHelper;
                        _presentViewController(ActiveFlowCoordinator, this, null, AnimationDirection.Horizontal, false);
                        BeatSaberMarkupLanguage.BSMLParser.instance.Parse(ContentBSML, gameObject, this);
                        return;
                    }
                }
            }

19 View Source File : Platform.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

private static void replacedignImplementations(Type platformDependant, string implementationName)
		{
			Type platformImplementation = platformDependant.GetNestedType(implementationName, bindings);
			// if (platformImplementation == null) return;

			FieldInfo[] fields = platformDependant.GetFields(bindings);
			foreach (FieldInfo field in fields)
			{
				Type fieldType = field.FieldType;
				string delegateName = fieldType.Name;
				MethodInfo methodInfo__internal = null;
				FieldInfo fieldInfo__internal = null;

				// TODO: This is mapping sodium.crypto_box to sodium.crypto_box__Internal. Should we also map them to sodium.__Internal.crypto_box?
				if (implementationName == "__Internal")
				{
					if (delegateName.EndsWith("_delegate"))
					{
						// YOU now have
						// public static readonly crypto_box_delegate box = crypto_box;

						// YOU need
						// public static readonly crypto_box_delegate box = crypto_box__Internal;

						delegateName = delegateName.Substring(0, delegateName.Length - "_delegate".Length);
						if (delegateName.Length > 0)
						{
							methodInfo__internal = platformDependant.GetMethod(delegateName + "__Internal", bindings);
						}
					}
				}
				if (methodInfo__internal == null && platformImplementation != null)
				{
					if (delegateName.EndsWith("Delegate"))
					{
						// YOU now have
						// public static readonly UnmanagedLibrary LoadUnmanagedLibraryDelegate;

						// YOU need
						// public static readonly LoadUnmanagedLibraryDelegate LoadUnmanagedLibrary 
						//     = Platform.__Internal.LoadUnmanagedLibrary;

						delegateName = delegateName.Substring(0, delegateName.Length - "Delegate".Length);

						methodInfo__internal = platformImplementation.GetMethod(delegateName, bindings);
					}
					else
					{
						methodInfo__internal = platformImplementation.GetMethod(field.Name, bindings);
					}

					if (methodInfo__internal == null)
					{
						fieldInfo__internal = platformImplementation.GetField(field.Name, bindings);
					}
				}

				if (methodInfo__internal != null)
				{
					var delegat = Delegate.CreateDelegate(fieldType, methodInfo__internal);
					field.SetValue(null, delegat);
				}
				else if (fieldInfo__internal != null)
				{
					object value = fieldInfo__internal.GetValue(null);
					field.SetValue(null, value);
				}
				// else { field.SetValue(null, null); }
			}
		}

19 View Source File : ZSymbol.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

private static void PickupConstantSymbols<T>(ref IDictionary<ZSymbol, string> symbols)
            where T : ZSymbol
		{
			Type type = typeof(T);

			FieldInfo[] fields = type.GetFields(BindingFlags.Static | BindingFlags.Public);

			Type codeType = type.GetNestedType("Code", BindingFlags.NonPublic);

			// Pickup constant symbols
			foreach (FieldInfo symbolField in fields.Where(f => typeof(ZSymbol).IsreplacedignableFrom(f.FieldType)))
			{
				FieldInfo symbolCodeField = codeType.GetField(symbolField.Name);
				if (symbolCodeField != null)
				{
					int symbolNumber = (int)symbolCodeField.GetValue(null);

				    var symbol = Activator.CreateInstance(
				        type,
				        BindingFlags.NonPublic | BindingFlags.Instance, 
				        null,
				        new object[] {symbolNumber},
				        null);
					symbolField.SetValue(null, symbol);
					symbols.Add((ZSymbol)symbol, symbolCodeField.Name);
				}
			}
		}

19 View Source File : LazyNode.cs
License : GNU General Public License v3.0
Project Creator : agolaszewski

public virtual void Bind(Expression<Func<TResult>> action)
        {
            if (((MemberExpression)action.Body).Member is PropertyInfo)
            {
                var propertyInfo = ((MemberExpression)action.Body).Member as PropertyInfo;

                var body = action.Body as MemberExpression;
                object projection = Expression.Lambda<Func<object>>(body.Expression).Compile()();

                _then = answer => { propertyInfo.SetValue(projection, answer); };
            }

            if (((MemberExpression)action.Body).Member is FieldInfo)
            {
                var fieldInfo = ((MemberExpression)action.Body).Member as FieldInfo;

                var body = action.Body as MemberExpression;
                object projection = Expression.Lambda<Func<object>>(body.Expression).Compile()();

                _then = answer => { fieldInfo.SetValue(projection, answer); };
            }
        }

19 View Source File : Node.cs
License : GNU General Public License v3.0
Project Creator : agolaszewski

public virtual IThen Bind(Expression<Func<TResult>> action)
        {
            if (((MemberExpression)action.Body).Member is PropertyInfo)
            {
                var propertyInfo = ((MemberExpression)action.Body).Member as PropertyInfo;

                var body = action.Body as MemberExpression;
                object projection = Expression.Lambda<Func<object>>(body.Expression).Compile()();

                _then = answer => { propertyInfo.SetValue(projection, answer); };
            }

            if (((MemberExpression)action.Body).Member is FieldInfo)
            {
                var fieldInfo = ((MemberExpression)action.Body).Member as FieldInfo;

                var body = action.Body as MemberExpression;
                object projection = Expression.Lambda<Func<object>>(body.Expression).Compile()();

                _then = answer => { fieldInfo.SetValue(projection, answer); };
            }

            return new ThenComponent(this);
        }

See More Examples