System.Reflection.ConstructorInfo.Invoke(object[])

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

901 Examples 7

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

[MonoModHook("Microsoft.Xna.Framework.GamerServices.PropertyDictionary XnaToFna.StubXDK.GamerServices.GamerPresenceExtensions::GetProperties(Microsoft.Xna.Framework.GamerServices.GamerPresence)")]
        public static /*PropertyDictionary*/ object GetProperties(/*GamerPresence*/ object presence) {
            // Return an empty dictionary.
            if (t_PropertyDictionary == null) {
                t_PropertyDictionary = StubXDKHelper.GamerServicesAsm.GetType("Microsoft.Xna.Framework.GamerServices.PropertyDictionary");
                ctor_PropertyDictionary = t_PropertyDictionary.GetConstructor(
                    BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance,
                    null,
                    new Type[] { typeof(Dictionary<string, object>) },
                    null
                );
            }
            return ctor_PropertyDictionary.Invoke(new object[] { new Dictionary<string, object>() });
        }

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

[MonoModHook("System.Collections.ObjectModel.ReadOnlyCollection`1<Microsoft.Xna.Framework.GamerServices.LeaderboardEntry> Microsoft.Xna.Framework.GamerServices.LeaderboardReader::get_Entries()")]
        public static object get_Entries(/*LeaderboardReader*/ object reader) {
            // Return an empty collection.
            if (t_LeaderboardEntry == null) {
                t_LeaderboardEntry = StubXDKHelper.GamerServicesAsm.GetType("Microsoft.Xna.Framework.GamerServices.LeaderboardEntry");
            }
            if (t_IList == null) {
                t_IList = typeof(IList<>).MakeGenericType(t_LeaderboardEntry);
            }
            if (t_List == null) {
                t_List = typeof(List<>).MakeGenericType(t_LeaderboardEntry);
                ctor_List = t_List.GetConstructor(
                    BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance,
                    null,
                    new Type[] { },
                    null
                );
            }
            if (t_ReadOnlyCollection == null) {
                t_ReadOnlyCollection = typeof(ReadOnlyCollection<>).MakeGenericType(t_LeaderboardEntry);
                ctor_ReadOnlyCollection = t_List.GetConstructor(
                    BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance,
                    null,
                    new Type[] { t_IList },
                    null
                );
            }
            return ctor_ReadOnlyCollection.Invoke(new object[] { ctor_List.Invoke(new object[] { }) });
        }

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

[MonoModHook("Microsoft.Xna.Framework.GamerServices.LeaderboardEntry Microsoft.Xna.Framework.GamerServices.LeaderboardWriter::GetLeaderboard(Microsoft.Xna.Framework.GamerServices.LeaderboardIdenreplacedy)")]
        public static /*LeaderboardEntry*/ object GetLeaderboard(/*LeaderboardWriter*/ object writer, /*LeaderboardIdenreplacedy*/ object idenreplacedy) {
            // Return an empty entry.
            if (t_LeaderboardEntry == null) {
                t_LeaderboardEntry = StubXDKHelper.GamerServicesAsm.GetType("Microsoft.Xna.Framework.GamerServices.LeaderboardEntry");
                ctor_LeaderboardEntry = t_LeaderboardEntry.GetConstructor(
                    BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance,
                    null,
                    new Type[] { },
                    null
                );
            }
            return ctor_LeaderboardEntry.Invoke(new object[] { });
        }

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

[MonoModHook("System.IAsyncResult Microsoft.Xna.Framework.Net.NetworkSession::BeginJoinInvited(System.Collections.Generic.IEnumerable`1<Microsoft.Xna.Framework.GamerServices.SignedInGamer>,System.AsyncCallback,System.Object)")]
        public static IAsyncResult BeginJoinInvited(/*IEnumerable<SignedInGamer>*/ object gamers, AsyncCallback cb, object obj) {
            // throw NetworkNotAvailableException
            if (t_NetworkNotAvailableException == null) {
                t_NetworkNotAvailableException = StubXDKHelper.GamerServicesAsm.GetType("Microsoft.Xna.Framework.Net.NetworkNotAvailableException");
                ctor_NetworkNotAvailableException = t_NetworkNotAvailableException.GetConstructor(
                    BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance,
                    null,
                    new Type[] { },
                    null
                );
            }
            throw (Exception) ctor_NetworkNotAvailableException.Invoke(new object[] { });
        }

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

[MonoModHook("System.IAsyncResult Microsoft.Xna.Framework.Net.NetworkSession::BeginJoinInvited(System.Int32,System.AsyncCallback,System.Object)")]
        public static IAsyncResult BeginJoinInvited(int a, AsyncCallback cb, object obj) {
            // throw NetworkNotAvailableException
            if (t_NetworkNotAvailableException == null) {
                t_NetworkNotAvailableException = StubXDKHelper.GamerServicesAsm.GetType("Microsoft.Xna.Framework.Net.NetworkNotAvailableException");
                ctor_NetworkNotAvailableException = t_NetworkNotAvailableException.GetConstructor(
                    BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance,
                    null,
                    new Type[] { },
                    null
                );
            }
            throw (Exception) ctor_NetworkNotAvailableException.Invoke(new object[] { });
        }

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

[MonoModHook("Microsoft.Xna.Framework.Net.NetworkSession Microsoft.Xna.Framework.Net.NetworkSession::EndJoinInvited(System.IAsyncResult)")]
        public static /*NetworkSession*/ object EndJoinInvited(IAsyncResult result) {
            // throw NetworkNotAvailableException
            if (t_NetworkNotAvailableException == null) {
                t_NetworkNotAvailableException = StubXDKHelper.GamerServicesAsm.GetType("Microsoft.Xna.Framework.Net.NetworkNotAvailableException");
                ctor_NetworkNotAvailableException = t_NetworkNotAvailableException.GetConstructor(
                    BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance,
                    null,
                    new Type[] { },
                    null
                );
            }
            throw (Exception) ctor_NetworkNotAvailableException.Invoke(new object[] { });
        }

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 : 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 : Function.cs
License : GNU Affero General Public License v3.0
Project Creator : 3CORESec

private void initConfig()
        {
            _alerts = new List<ISender>();
            config = JsonConvert.DeserializeObject<Config>(File.ReadAllText("config.json"));
            if (string.IsNullOrEmpty(config.SlackPath))
                config.SlackPath = Environment.GetEnvironmentVariable("SLACKPATH");
            if (string.IsNullOrEmpty(config.WebhookChannel))
                config.WebhookChannel = Environment.GetEnvironmentVariable("WEBHOOKCHANNEL");
            if (string.IsNullOrEmpty(config.WebHookToken))
                config.WebHookToken = Environment.GetEnvironmentVariable("WEBHOOKTOKEN");
            if (string.IsNullOrEmpty(config.PostUrl))
                config.PostUrl = Environment.GetEnvironmentVariable("POSTURL");
            var type = typeof(ISender);
            var types = AppDomain.CurrentDomain.Getreplacedemblies()
                .SelectMany(s => s.GetTypes())
                .Where(p => type.IsreplacedignableFrom(p) && !p.IsInterface && !p.IsAbstract);
            types.ToList().ForEach(type => {
                ConstructorInfo ctor = type.GetConstructor(new[] { typeof(Storage<SessionLog>), typeof(Config), typeof(IMemoryCache) });
                ISender instance = ctor.Invoke(new object[] { _storage, config, memoryCache }) as ISender;
                _alerts.Add(instance);
            });
        }

19 View Source File : TypeFuzzer.cs
License : Apache License 2.0
Project Creator : 42skillz

private T InstantiateAndFuzzViaConstructorWithBiggestNumberOfParameters<T>(ConstructorInfo constructor, int recursionLevel)
        {
            var constructorParameters = PrepareFuzzedParametersForThisConstructor(constructor, recursionLevel);
            var instance = constructor.Invoke(constructorParameters);
            return (T)instance;
        }

19 View Source File : TypeFuzzer.cs
License : Apache License 2.0
Project Creator : 42skillz

private T InstantiateAndFuzzViaPropertiesWhenTheyHaveSetters<T>(ConstructorInfo constructor, int recursionLevel,
            Type genericType, object instance = null)
        {
            if (instance == null)
            {
                instance = constructor.Invoke(new object[0]);
            }

            var propertyInfos = genericType.GetProperties().Where(prop => prop.CanWrite);
            foreach (var propertyInfo in propertyInfos)
            {
                var propertyType = propertyInfo.PropertyType;
                var propertyValue = FuzzAnyDotNetType(Type.GetTypeCode(propertyType), propertyType, recursionLevel);

                propertyInfo.SetValue(instance, propertyValue);
            }

            return (T)instance;
        }

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

public object Read(object value, ProtoReader source)
        {
            object[] values = new object[members.Length];
            bool invokeCtor = false;
            if (value == null)
            {
                invokeCtor = true;
            }
            for (int i = 0; i < values.Length; i++)
                values[i] = GetValue(value, i);
            int field;
            while ((field = source.ReadFieldHeader()) > 0)
            {
                invokeCtor = true;
                if (field <= tails.Length)
                {
                    IProtoSerializer tail = tails[field - 1];
                    values[field - 1] = tails[field - 1].Read(tail.RequiresOldValue ? values[field - 1] : null, source);
                }
                else
                {
                    source.SkipField();
                }
            }
            return invokeCtor ? ctor.Invoke(values) : value;
        }

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

internal static object ParseValue(Type type, string json) {
            if (type == typeof(string)) {
                if (json.Length <= 2)
                    return string.Empty;
                string str = json.Substring(1, json.Length - 2);
                return str.Replace("\\\\", "\"\"").Replace("\\", string.Empty).Replace("\"\"", "\\");
            }
            if (type == typeof(int)) {
                int result;
                int.TryParse(json, out result);
                return result;
            }
            if (type == typeof(float)) {
                float result;
                float.TryParse(json, out result);
                return result;
            }
            if (type == typeof(double)) {
                double result;
                double.TryParse(json, out result);
                return result;
            }
            if (type == typeof(bool)) {
                return json.ToLower() == "true";
            }
            if (json == "null") {
                return null;
            }
            if (type.IsArray) {
                Type arrayType = type.GetElementType();
                if (json[0] != '[' || json[json.Length - 1] != ']')
                    return null;

                List<string> elems = Split(json);
                Array newArray = Array.CreateInstance(arrayType, elems.Count);
                for (int i = 0; i < elems.Count; i++)
                    newArray.SetValue(ParseValue(arrayType, elems[i]), i);
                splitArrayPool.Push(elems);
                return newArray;
            }
            if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>)) {
                Type listType = type.GetGenericArguments()[0];
                if (json[0] != '[' || json[json.Length - 1] != ']')
                    return null;

                List<string> elems = Split(json);
                var list = (IList)type.GetConstructor(new Type[] { typeof(int) }).Invoke(new object[] { elems.Count });
                for (int i = 0; i < elems.Count; i++)
                    list.Add(ParseValue(listType, elems[i]));
                splitArrayPool.Push(elems);
                return list;
            }
            if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<,>)) {
                Type keyType, valueType;
                {
                    Type[] args = type.GetGenericArguments();
                    keyType = args[0];
                    valueType = args[1];
                }

                //Refuse to parse dictionary keys that aren't of type string
                if (keyType != typeof(string))
                    return null;
                //Must be a valid dictionary element
                if (json[0] != '{' || json[json.Length - 1] != '}')
                    return null;
                //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 null;

                var dictionary = (IDictionary)type.GetConstructor(new Type[] { typeof(int) }).Invoke(new object[] { elems.Count / 2 });
                for (int i = 0; i < elems.Count; i += 2) {
                    if (elems[i].Length <= 2)
                        continue;
                    string keyValue = elems[i].Substring(1, elems[i].Length - 2);
                    object val = ParseValue(valueType, elems[i + 1]);
                    dictionary.Add(keyValue, val);
                }
                return dictionary;
            }
            if (type == typeof(object)) {
                return ParseAnonymousValue(json);
            }
            if (json[0] == '{' && json[json.Length - 1] == '}') {
                return ParseObject(type, json);
            }

            return null;
        }

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

public static bool TryPrepareMethod(MethodBase method, RuntimeMethodHandle handle)
        {
            // First, try the good ol' RuntimeHelpers.PrepareMethod.
            if (PrepareMethod != null)
            {
                PrepareMethod(handle);
                return true;
            }

            // No chance, we gotta go lower.
            // Invoke the method with uninitialized arguments.
            object sender = null;

            object[] GetArguments(ParameterInfo[] parameters)
            {
                object[] args = new object[parameters.Length];

                for (int i = 0; i < parameters.Length; i++)
                {
                    ParameterInfo param = parameters[i];

                    if (param.HasDefaultValue)
                        args[i] = param.DefaultValue;
                    else if (param.ParameterType.GetTypeInfo().IsValueType)
                        args[i] = Activator.CreateInstance(param.ParameterType);
                    else
                        args[i] = null;
                }

                return args;
            }

            if (!method.IsStatic)
            {
                // Gotta make the instance
                Type declaringType = method.DeclaringType;

                if (declaringType.GetTypeInfo().IsValueType)
                {
                    sender = Activator.CreateInstance(declaringType);
                }
                else if (declaringType.GetTypeInfo().IsAbstract)
                {
                    // Overkill solution: Find a type in the replacedembly that implements the declaring type,
                    // and use it instead.
                    throw new InvalidOperationException("Cannot manually JIT a method");
                }
                else if (GetUninitializedObject != null)
                {
                    sender = GetUninitializedObject(declaringType);
                }
                else
                {
                    /* TODO
                     * Since I just made the whole 'gotta JIT the method' step mandatory
                     * in the MethodRedirection ctor, i should make sure this always returns true.
                     * That means looking up every type for overriding types for the throwing step above,
                     * and testing every possible constructor to create the instance.
                     * 
                     * Additionally, if we want to go even further, we can repeat this step for every
                     * single argument of the ctor, thus making sure that we end up having an actual clreplaced.
                     * In this case, unless the user wants to instantiate an abstract clreplaced with no overriding clreplaced,
                     * everything'll work. HOWEVER, performances would be less-than-ideal. A simple Redirection
                     * may mean scanning the replacedembly a dozen times for overriding types, calling their constructors
                     * hundreds of times, knowing that all of them will be slow (Reflection + Try/Catch blocks aren't
                     * perfs-friendly).
                     */
                    ConstructorInfo ctor = declaringType.GetConstructor(Type.EmptyTypes);

                    if (ctor != null)
                    {
                        sender = ctor.Invoke(null);
                    }
                    else
                    {
                        ConstructorInfo[] ctors = declaringType.GetConstructors(ALL_INSTANCE);

                        Array.Sort(ctors, (a, b) => a.GetParameters().Length.CompareTo(b.GetParameters().Length));

                        ctor = ctors[0];

                        try
                        {
                            sender = ctor.Invoke(GetArguments(ctor.GetParameters()));
                        }
                        catch (TargetInvocationException)
                        {
                            // Nothing we can do, give up.
                            return false;
                        }
                    }
                }
            }

            try
            {
                method.Invoke(sender, GetArguments(method.GetParameters()));
            }
            catch (TargetInvocationException)
            {
                // That's okay.
            }

            return true;
        }

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

public object InvokeOriginal(object obj, params object[] args)
        {
            IntPtr methodStart = originalMethodStart;
            bool wasRedirecting = isRedirecting;

            if (wasRedirecting)
                CopyToStart(originalBytes, methodStart);

            try
            {
                if (obj == null && Original.IsConstructor)
                    return ((ConstructorInfo)Original).Invoke(args);

                return Original.Invoke(obj, args);
            }
            finally
            {
                if (wasRedirecting)
                    CopyToStart(replacementBytes, methodStart);
            }
        }

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

protected VirtualStateMachine Compile()
        {
            LambdaExpression lambda = ToLambda();
            VirtualStateMachine vsm = (VirtualStateMachine)_vsmCtor.Invoke(null);

            vsm.Initialize(trackingVisitor.Variables.ToArray(), labelTargets.Count + 1, lambda.Compile());

            return vsm;
        }

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

public static bool TryPrepareMethod(MethodBase method, RuntimeMethodHandle handle)
            {
                // First, try the good ol' RuntimeHelpers.PrepareMethod.
                if (PrepareMethod != null)
                {
                    PrepareMethod(handle);
                    return true;
                }

                // No chance, we gotta go lower.
                // Invoke the method with uninitialized arguments.
                object sender = null;

                object[] GetArguments(ParameterInfo[] parameters)
                {
                    object[] args = new object[parameters.Length];

                    for (int i = 0; i < parameters.Length; i++)
                    {
                        ParameterInfo param = parameters[i];

                        if (param.HasDefaultValue)
                            args[i] = param.DefaultValue;
                        else if (param.ParameterType.GetTypeInfo().IsValueType)
                            args[i] = Activator.CreateInstance(param.ParameterType);
                        else
                            args[i] = null;
                    }

                    return args;
                }

                if (!method.IsStatic)
                {
                    // Gotta make the instance
                    Type declaringType = method.DeclaringType;

                    if (declaringType.GetTypeInfo().IsValueType)
                    {
                        sender = Activator.CreateInstance(declaringType);
                    }
                    else if (declaringType.GetTypeInfo().IsAbstract)
                    {
                        // Overkill solution: Find a type in the replacedembly that implements the declaring type,
                        // and use it instead.
                        throw new InvalidOperationException("Cannot manually JIT a method");
                    }
                    else if (GetUninitializedObject != null)
                    {
                        sender = GetUninitializedObject(declaringType);
                    }
                    else
                    {
                        /* TODO
                         * Since I just made the whole 'gotta JIT the method' step mandatory
                         * in the MethodRedirection ctor, i should make sure this always returns true.
                         * That means looking up every type for overriding types for the throwing step above,
                         * and testing every possible constructor to create the instance.
                         * 
                         * Additionally, if we want to go even further, we can repeat this step for every
                         * single argument of the ctor, thus making sure that we end up having an actual clreplaced.
                         * In this case, unless the user wants to instantiate an abstract clreplaced with no overriding clreplaced,
                         * everything'll work. HOWEVER, performances would be less-than-ideal. A simple Redirection
                         * may mean scanning the replacedembly a dozen times for overriding types, calling their constructors
                         * hundreds of times, knowing that all of them will be slow (Reflection + Try/Catch blocks aren't
                         * perfs-friendly).
                         */
                        ConstructorInfo ctor = declaringType.GetConstructor(Type.EmptyTypes);

                        if (ctor != null)
                        {
                            sender = ctor.Invoke(null);
                        }
                        else
                        {
                            ConstructorInfo[] ctors = declaringType.GetConstructors(ALL_INSTANCE);

                            Array.Sort(ctors, (a, b) => a.GetParameters().Length.CompareTo(b.GetParameters().Length));

                            ctor = ctors[0];

                            try
                            {
                                sender = ctor.Invoke(GetArguments(ctor.GetParameters()));
                            }
                            catch (TargetInvocationException)
                            {
                                // Nothing we can do, give up.
                                return false;
                            }
                        }
                    }
                }

                try
                {
                    method.Invoke(sender, GetArguments(method.GetParameters()));
                }
                catch (TargetInvocationException)
                {
                    // That's okay.
                }

                return true;
            }

19 View Source File : FolderSelectDialog.cs
License : MIT License
Project Creator : 86Box

public static ShowDialogResult Show(IntPtr ownerHandle, string initialDirectory, string replacedle)
            {
                var openFileDialog = new OpenFileDialog
                {
                    AddExtension = false,
                    CheckFileExists = false,
                    DereferenceLinks = true,
                    Filter = c_foldersFilter,
                    InitialDirectory = initialDirectory,
                    Multiselect = false,
                    replacedle = replacedle
                };

                var iFileDialog = s_createVistaDialogMethodInfo.Invoke(openFileDialog, new object[] { });
                s_onBeforeVistaDialogMethodInfo.Invoke(openFileDialog, new[] { iFileDialog });
                s_setOptionsMethodInfo.Invoke(iFileDialog, new object[] { (uint)s_getOptionsMethodInfo.Invoke(openFileDialog, new object[] { }) | s_fosPickFoldersBitFlag });
                var adviseParametersWithOutputConnectionToken = new[] { s_vistaDialogEventsConstructorInfo.Invoke(new object[] { openFileDialog }), 0U };
                s_adviseMethodInfo.Invoke(iFileDialog, adviseParametersWithOutputConnectionToken);

                try
                {
                    int retVal = (int)s_showMethodInfo.Invoke(iFileDialog, new object[] { ownerHandle });
                    return new ShowDialogResult
                    {
                        Result = retVal == 0,
                        FileName = openFileDialog.FileName
                    };
                }
                finally
                {
                    s_unAdviseMethodInfo.Invoke(iFileDialog, new[] { adviseParametersWithOutputConnectionToken[1] });
                }
            }

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

public T GetOrCreateDna<T>()
				where T : UMADnaBase
			{
				T res = GetDna<T>();
				if (res == null)
				{
					res = typeof(T).GetConstructor(System.Type.EmptyTypes).Invoke(null) as T;
					umaDna.Add(res.DNATypeHash, res);
					dnaValues.Add(res);
				}
				return res;
			}

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

public UMADnaBase GetOrCreateDna(Type type)
			{
				UMADnaBase dna;
				var typeNameHash = UMAUtils.StringToHash(type.Name);
				if (umaDna.TryGetValue(typeNameHash, out dna))
				{
					return dna;
				}

				dna = type.GetConstructor(System.Type.EmptyTypes).Invoke(null) as UMADnaBase;
				umaDna.Add(typeNameHash, dna);
				dnaValues.Add(dna);
				return dna;
			}

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

public UMADnaBase GetOrCreateDna(Type type, int dnaTypeHash)
			{
				UMADnaBase dna;
				if (umaDna.TryGetValue(dnaTypeHash, out dna))
				{
					return dna;
				}

				dna = type.GetConstructor(System.Type.EmptyTypes).Invoke(null) as UMADnaBase;
				dna.DNATypeHash = dnaTypeHash;
				umaDna.Add(dnaTypeHash, dna);
				dnaValues.Add(dna);
				return dna;
			}

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

private Exception UnWrap(Exception innerException)
        {
            Exception exception = null;
            if (this.Type != null)  // m_type is typically null when this.Type getter is hit from here, so the LoadType method will get invoked here.
            {
                try
                {
                    Object[] args = null;

                    ConstructorInfo info = GetMatchingConstructor(new[] { typeof(WrappedException) });
                    if (info != null)
                    {
                        // a constructor overload on an exception that takes a WrappedException, is useful
                        // in cases where the other constructors manipulate the string that we preplaced in,
                        // which we do not want to happen when unwrapping an exception.
                        args = new object[] { this };
                    }
                    else
                    {
                        info = GetMatchingConstructor(new[] { typeof(String), typeof(Exception) });
                        if (info != null)
                        {
                            args = new object[] { Message, innerException };
                        }
                        else
                        {
                            //try just string
                            info = GetMatchingConstructor(new[] { typeof(String) });
                            if (info != null)
                            {
                                args = new object[] { Message };
                            }
                            else
                            {
                                //try default constructor
                                info = GetMatchingConstructor(new Type[0]);
                            }
                        }
                    }
                    if (info != null)
                    {
                        exception = info.Invoke(args) as Exception;
                        // only check exceptions that derive from VssExceptions, since we don't have control
                        // to make code changes to exceptions that we don't own.
                        Debug.replacedert(!(exception is VssException) || exception.Message == Message,
                            "The unwrapped exception message does not match the original exception message.",
                            "Type: {0}{1}Expected: {2}{1}Actual: {3}{1}{1}This can happen if the exception has a contructor that manipulates the input string.  You can work around this by creating a constructor that takes in a WrappedException which sets the message verbatim and optionally the inner exception.",
                            exception.GetType(),
                            Environment.NewLine,
                            Message,
                            exception.Message);
                    }
                }
                catch (Exception)
                { }
            }
            return exception;
        }

19 View Source File : AsOfSqlExpressionFactory.cs
License : MIT License
Project Creator : Adam-Langley

public override SelectExpression Select(IEnreplacedyType enreplacedyType)
        {
            if (enreplacedyType.FindAnnotation(SqlServerAsOfEnreplacedyTypeBuilderExtensions.ANNOTATION_TEMPORAL) != null)
            {
                var asOfTableExpression = new AsOfTableExpression(
                    enreplacedyType.GetTableName(),
                    enreplacedyType.GetSchema(),
                    enreplacedyType.GetTableName().ToLower().Substring(0, 1));

                var selectContructor = typeof(SelectExpression).GetConstructor(BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance, null, new Type[] { typeof(IEnreplacedyType), typeof(TableExpressionBase) }, null);
                var select = (SelectExpression)selectContructor.Invoke(new object[] { enreplacedyType, asOfTableExpression });

                var privateInitializer = typeof(SqlExpressionFactory).GetMethod("AddConditions", BindingFlags.NonPublic | BindingFlags.Instance);
                privateInitializer.Invoke(this, new object[] { select, enreplacedyType, null, null });

                return select;
            }

            return base.Select(enreplacedyType);
        }

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

public bool TryLoadFromWMV(string filePath, out Video video)
        {
            video = null;
            Monitor.Log($"Loading wmv: {filePath}");

            using (AsfMojo.File.AsfFile asfFile = new AsfMojo.File.AsfFile(filePath))
            {
                int duration = (int)asfFile.PacketConfiguration.Duration * 1000, width = asfFile.PacketConfiguration.ImageWidth, height = asfFile.PacketConfiguration.ImageHeight;
                Monitor.Log($"Duration: {duration}");
                if (asfFile.GetAsfObjectByType(AsfGuid.ASF_Metadata_Object).FirstOrDefault() is AsfMetadataObject metadataObject)
                {
                    foreach(AsfMetadataObject o in asfFile.GetAsfObjectByType(AsfGuid.ASF_Metadata_Object))
                    {
                        Monitor.Log($"object: {o.Name}"); 
                        foreach (AsfProperty p in o.DescriptionRecords)
                        {
                            Monitor.Log($"property: {p.Name}");
                        }
                    }
                    ConstructorInfo videoConstructor = typeof(Video).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { typeof(GraphicsDevice), typeof(string), typeof(int), typeof(int), typeof(int), typeof(float), typeof(VideoSoundtrackType) }, null);
                    Monitor.Log($"Constructor: {videoConstructor != null}");
                    if (videoConstructor?.Invoke(new object[] { Game1.graphics.GraphicsDevice, filePath, duration, width, height, -1, VideoSoundtrackType.MusicAndDialog }) is Video v)
                    {
                        video = v;
                        Monitor.Log($"loaded video: {video != null}");
                    }
                }
            }

            return video is Video;
        }

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

private void InvokeNormal(DarksVMContext ctx, MethodBase targetMethod, byte opCode, ref uint sp, out ExecutionState state)
        {
            var _sp = sp;
            var parameters = targetMethod.GetParameters();
            object self = null;
            var args = new object[parameters.Length];
            if(opCode == DarksVMConstants.ECALL_CALL && targetMethod.IsVirtual)
            {
                var indexOffset = targetMethod.IsStatic ? 0 : 1;
                args = new object[parameters.Length + indexOffset];
                for(var i = parameters.Length - 1; i >= 0; i--)
                    args[i + indexOffset] = PopObject(ctx, parameters[i].ParameterType, ref sp);
                if(!targetMethod.IsStatic)
                    args[0] = PopObject(ctx, targetMethod.DeclaringType, ref sp);

                targetMethod = DirectCall.GetDirectInvocationProxy(targetMethod);
            }
            else
            {
                args = new object[parameters.Length];
                for(var i = parameters.Length - 1; i >= 0; i--)
                    args[i] = PopObject(ctx, parameters[i].ParameterType, ref sp);
                if(!targetMethod.IsStatic && opCode != DarksVMConstants.ECALL_NEWOBJ)
                {
                    self = PopObject(ctx, targetMethod.DeclaringType, ref sp);

                    if(self != null && !targetMethod.DeclaringType.IsInstanceOfType(self))
                    {
                        // ConfuserEx sometimes produce this to cirreplacedvent peverify (see ref proxy)
                        // Reflection won't allow it, so use typed invoke
                        InvokeTyped(ctx, targetMethod, opCode, ref _sp, out state);
                        return;
                    }
                }
            }

            object result;
            if(opCode == DarksVMConstants.ECALL_NEWOBJ)
            {
                try
                {
                    result = ((ConstructorInfo) targetMethod).Invoke(args);
                }
                catch(TargetInvocationException ex)
                {
                    EHHelper.Rethrow(ex.InnerException, null);
                    throw;
                }
            }
            else
            {
                if(!targetMethod.IsStatic && self == null)
                    throw new NullReferenceException();

                Type selfType;
                if(self != null && (selfType = self.GetType()).IsArray && targetMethod.Name == "SetValue")
                {
                    Type valueType;
                    if(args[0] == null)
                        valueType = selfType.GetElementType();
                    else
                        valueType = args[0].GetType();
                    ArrayStoreHelpers.SetValue((Array) self, (int) args[1], args[0], valueType, selfType.GetElementType());
                    result = null;
                }
                else
                {
                    try
                    {
                        result = targetMethod.Invoke(self, args);
                    }
                    catch(TargetInvocationException ex)
                    {
                        DarksVMDispatcher.DoThrow(ctx, ex.InnerException);
                        throw;
                    }
                }
            }

            if(targetMethod is MethodInfo && ((MethodInfo) targetMethod).ReturnType != typeof(void)) ctx.Stack[++sp] = DarksVMSlot.FromObject(result, ((MethodInfo) targetMethod).ReturnType);
            else if(opCode == DarksVMConstants.ECALL_NEWOBJ) ctx.Stack[++sp] = DarksVMSlot.FromObject(result, targetMethod.DeclaringType);

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

19 View Source File : PluginManager.cs
License : GNU General Public License v2.0
Project Creator : afrantzis

private void AddPluginFile(string file)
	{
		try {
			replacedembly asm = replacedembly.LoadFile(file);
			Type[] types = asm.GetTypes();

			foreach(Type t in types) {
				if (t.BaseType == pluginType) {
					//Console.WriteLine("    Found Type {0}", t.FullName);
					ConstructorInfo ctor = t.GetConstructor(ctorArgTypes);
					AddToPluginCollection((Plugin)ctor.Invoke(ctorArgs));
				}
			}
		}
		catch (Exception e) {
			System.Console.WriteLine(e.Message);
		}

	}

19 View Source File : IdentityBuilderExtensions.cs
License : Apache License 2.0
Project Creator : Aguafrommars

private static void AddStores(IServiceCollection services, Type userType, Type roleType, Func<IServiceProvider, IDatabase> getDatabase)
        {
            var idenreplacedyUserType = FindGenericBaseType(userType, typeof(IdenreplacedyUser<>));
            if (idenreplacedyUserType == null)
            {
                throw new InvalidOperationException("AddEnreplacedyFrameworkStores can only be called with a user that derives from IdenreplacedyUser<TKey>.");
            }

            var keyType = idenreplacedyUserType.GenericTypeArguments[0];
        
            var userOnlyStoreType = typeof(UserOnlyStore<,>).MakeGenericType(userType, keyType);

            if (roleType != null)   
            {
                var idenreplacedyRoleType = FindGenericBaseType(roleType, typeof(IdenreplacedyRole<>));
                if (idenreplacedyRoleType == null)
                {
                    throw new InvalidOperationException("AddEnreplacedyFrameworkStores can only be called with a role that derives from IdenreplacedyRole<TKey>.");
                }

                var userStoreType = typeof(UserStore<,,>).MakeGenericType(userType, roleType, keyType);
                var roleStoreType = typeof(RoleStore<,>).MakeGenericType(roleType, keyType);

                services.TryAddScoped(typeof(UserOnlyStore<,>).MakeGenericType(userType, keyType), provider => CreateStoreInstance(userOnlyStoreType, getDatabase(provider), provider.GetService<IdenreplacedyErrorDescriber>()));
                services.TryAddScoped(typeof(IUserStore<>).MakeGenericType(userType), provider => userStoreType.GetConstructor(new Type[] { typeof(IDatabase), userOnlyStoreType, typeof(IdenreplacedyErrorDescriber) })
                    .Invoke(new object[] { getDatabase(provider), provider.GetService(userOnlyStoreType), provider.GetService<IdenreplacedyErrorDescriber>() }));
                services.TryAddScoped(typeof(IRoleStore<>).MakeGenericType(roleType), provider => CreateStoreInstance(roleStoreType, getDatabase(provider), provider.GetService<IdenreplacedyErrorDescriber>()));
            }
            else
            {   // No Roles
                services.TryAddScoped(typeof(IUserStore<>).MakeGenericType(userType), provider => CreateStoreInstance(userOnlyStoreType, getDatabase(provider), provider.GetService<IdenreplacedyErrorDescriber>()));
            }
        }

19 View Source File : IdentityBuilderExtensions.cs
License : Apache License 2.0
Project Creator : Aguafrommars

private static object CreateStoreInstance(Type storeType, IDatabase db, IdenreplacedyErrorDescriber errorDescriber)
        {
            var constructor = storeType.GetConstructor(new Type[] { typeof(IDatabase), typeof(IdenreplacedyErrorDescriber)});
            return constructor.Invoke(new object[] { db, errorDescriber });
        }

19 View Source File : ServiceProviderExtensions.cs
License : Apache License 2.0
Project Creator : Aguafrommars

public static object CreateUserOnlyStore(this IServiceProvider provider, Type userOnlyStoreType)
        {
            userOnlyStoreType = userOnlyStoreType ?? throw new ArgumentNullException(nameof(userOnlyStoreType));
            var userStore = provider.GetRequiredService<IAdminStore<User>>();
            var userClaimStore = provider.GetRequiredService<IAdminStore<UserClaim>>();
            var userLoginStore = provider.GetRequiredService<IAdminStore<UserLogin>>();
            var userTokenStore = provider.GetRequiredService<IAdminStore<UserToken>>();
            var errorDescriber = provider.GetRequiredService<IdenreplacedyErrorDescriber>();
            var constructor = userOnlyStoreType.GetConstructor(new Type[]
            {
                typeof(IAdminStore<User>),
                typeof(IAdminStore<UserClaim>),
                typeof(IAdminStore<UserLogin>),
                typeof(IAdminStore<UserToken>),
                typeof(IdenreplacedyErrorDescriber)
            });
            return constructor.Invoke(new object[]
            {
                userStore,
                userClaimStore,
                userLoginStore,
                userTokenStore,
                errorDescriber,
            });
        }

19 View Source File : UserStoreTest.cs
License : Apache License 2.0
Project Creator : Aguafrommars

protected override void AddUserStore(IServiceCollection services, object context = null)
        {            
            var userType = typeof(TestUser);
            var keyType = typeof(string);
            var userStoreType = typeof(UserStore<,>).MakeGenericType(userType, typeof(TestRole));
            var userOnlyStoreType = typeof(UserOnlyStore<,>).MakeGenericType(userType, keyType);
            services.TryAddSingleton(typeof(UserOnlyStore<,>).MakeGenericType(userType, keyType), provider => userOnlyStoreType.GetConstructor(new Type[] { typeof(IDatabase), typeof(IdenreplacedyErrorDescriber) })
                .Invoke(new object[] { _fixture.Database, null }));
            services.TryAddSingleton(typeof(IUserStore<>).MakeGenericType(userType), provider => userStoreType.GetConstructor(new Type[] { typeof(IDatabase), userOnlyStoreType, typeof(IdenreplacedyErrorDescriber) })
                .Invoke(new object[] { _fixture.Database, provider.GetService(userOnlyStoreType), null }));
        }

19 View Source File : ServiceProviderExtensions.cs
License : Apache License 2.0
Project Creator : Aguafrommars

public static object CreateRoleStore(this IServiceProvider provider, Type roleStoreType)
        {
            roleStoreType = roleStoreType ?? throw new ArgumentNullException(nameof(roleStoreType));
            var RoleClaimeStore = provider.GetRequiredService<IAdminStore<RoleClaim>>();
            var roleStore = provider.GetRequiredService<IAdminStore<Role>>();
            var errorDescriber = provider.GetRequiredService<IdenreplacedyErrorDescriber>();
            var constructor = roleStoreType.GetConstructor(new Type[]
            {
                typeof(IAdminStore<Role>),
                typeof(IAdminStore<RoleClaim>),
                typeof(IdenreplacedyErrorDescriber)
            });
            return constructor.Invoke(new object[]
            {
                roleStore,
                RoleClaimeStore,
                errorDescriber
            });
        }

19 View Source File : ServiceProviderExtensions.cs
License : Apache License 2.0
Project Creator : Aguafrommars

public static object CreateUserStore(this IServiceProvider provider, Type userOnlyStoreType, Type userStoreType)
        {
            userOnlyStoreType = userOnlyStoreType ?? throw new ArgumentNullException(nameof(userOnlyStoreType));
            userStoreType = userStoreType ?? throw new ArgumentNullException(nameof(userStoreType));
            var userStore = provider.GetRequiredService<IAdminStore<Role>>();
            var userRoleStore = provider.GetRequiredService<IAdminStore<UserRole>>();
            var userOnlyStore = provider.GetRequiredService(userOnlyStoreType);
            var errorDescriber = provider.GetRequiredService<IdenreplacedyErrorDescriber>();
            var constructor = userStoreType.GetConstructor(new Type[]
            {
                typeof(IAdminStore<Role>),
                typeof(IAdminStore<UserRole>),
                userOnlyStoreType,
                typeof(IdenreplacedyErrorDescriber)
            });
            return constructor.Invoke(new object[]
            {
                userStore,
                userRoleStore,
                userOnlyStore,
                errorDescriber
            });
        }

19 View Source File : ServiceCollectionExtensions.cs
License : Apache License 2.0
Project Creator : Aguafrommars

private static object CreateStore(Func<IServiceProvider, Task<HttpClient>> getHttpClient, IServiceProvider provider, Type enreplacedyType)
        {
            var adminStoreType = typeof(AdminStore<>)
                        .MakeGenericType(enreplacedyType.GetTypeInfo()).GetTypeInfo();

            var loggerType = typeof(ILogger<>).MakeGenericType(adminStoreType);
            return adminStoreType.GetConstructors()[0]
                .Invoke(new object[] { getHttpClient.Invoke(provider), provider.GetRequiredService(loggerType) });
        }

19 View Source File : SnowflakeArrayAsDictionaryJsonConverter.cs
License : MIT License
Project Creator : Aiko-IT-Systems

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var constructor = objectType.GetTypeInfo().DeclaredConstructors
                .FirstOrDefault(e => !e.IsStatic && e.GetParameters().Length == 0);

            var dict = constructor.Invoke(new object[] {});

            // the default name of an indexer is "Item"
            var properties = objectType.GetTypeInfo().GetDeclaredProperty("Item");

            var entries = (IEnumerable) serializer.Deserialize(reader, objectType.GenericTypeArguments[1].MakeArrayType());
            foreach (var entry in entries)
            {
                properties.SetValue(dict, entry, new object[]
                {
                    (entry as SnowflakeObject)?.Id
                    ?? (entry as DiscordVoiceState)?.UserId
                    ?? throw new InvalidOperationException($"Type {entry?.GetType()} is not deserializable")
                });
            }

            return dict;
        }

19 View Source File : AutoFakeIt.cs
License : MIT License
Project Creator : akamud

public T Generate<T>() where T : clreplaced
        {
            var constructors = typeof(T).GetConstructors()
                .OrderByDescending(ctor => ctor.GetParameters().Length)
                .ToList();

            Exception? lastThrownException = null;
            foreach (var ctor in constructors)
            {
                try
                {
                    var candidateFakeObjects = GenerateCandidateFakeObjects(ctor);

                    var generatedObject = (T)ctor.Invoke(candidateFakeObjects.Values.ToArray());

                    InsertMissingFakedObjects(candidateFakeObjects);

                    return generatedObject;
                }
                catch (Exception ex)
                {
                    lastThrownException = ex;
                    // Keep looking for a suitable constructor
                }
            }

            throw new ArgumentException($"No suitable constructor found for type '{typeof(T)}'.", lastThrownException);
        }

19 View Source File : LateBoundReflectionDelegateFactory.cs
License : MIT License
Project Creator : akaskela

public override Func<T> CreateDefaultConstructor<T>(Type type)
        {
            ValidationUtils.ArgumentNotNull(type, nameof(type));

            if (type.IsValueType())
            {
                return () => (T)Activator.CreateInstance(type);
            }

            ConstructorInfo constructorInfo = ReflectionUtils.GetDefaultConstructor(type, true);

            return () => (T)constructorInfo.Invoke(null);
        }

19 View Source File : LateBoundReflectionDelegateFactory.cs
License : MIT License
Project Creator : akaskela

public override ObjectConstructor<object> CreateParameterizedConstructor(MethodBase method)
        {
            ValidationUtils.ArgumentNotNull(method, nameof(method));

            ConstructorInfo c = method as ConstructorInfo;
            if (c != null)
            {
                // don't convert to method group to avoid medium trust issues
                // https://github.com/JamesNK/Newtonsoft.Json/issues/476
                return a =>
                {
                    object[] args = a;
                    return c.Invoke(args);
                };
            }

            return a => method.Invoke(null, a);
        }

19 View Source File : EventStoreJournal.cs
License : Apache License 2.0
Project Creator : AkkaNetContrib

private IEventAdapter BuildDefaultJournalAdapter()
        {
            Func<DefaultEventAdapter> getDefaultAdapter = () => new DefaultEventAdapter(_serialization);

            if (_settings.Adapter.ToLowerInvariant() == "default")
            {
                return getDefaultAdapter();
            }
            else if (_settings.Adapter.ToLowerInvariant() == "legacy")
            {
                return new LegacyEventAdapter(_serialization);
            }

            try
            {
                var journalAdapterType = Type.GetType(_settings.Adapter);
                if (journalAdapterType == null)
                {
                    _log.Error(
                        $"Unable to find type [{_settings.Adapter}] Adapter for EventStoreJournal. Is the replacedembly referenced properly? Falling back to default");
                    return getDefaultAdapter();
                }

                var adapterConstructor = journalAdapterType.GetConstructor(new[] { typeof(Akka.Serialization.Serialization) });
                
                IEventAdapter journalAdapter = (adapterConstructor != null 
                    ? adapterConstructor.Invoke(new object[] { _serialization }) 
                    : Activator.CreateInstance(journalAdapterType)) as IEventAdapter;

                if (journalAdapter == null)
                {
                    _log.Error(
                        $"Unable to create instance of type [{journalAdapterType.replacedemblyQualifiedName}] Adapter for EventStoreJournal. Do you have an empty constructor, or one that takes in Akka.Serialization.Serialization? Falling back to default.");
                    return getDefaultAdapter();
                }

                return journalAdapter;
            }
            catch (Exception e)
            {
                _log.Error(e, "Error loading Adapter for EventStoreJournal. Falling back to default");
                return getDefaultAdapter();
            }
        }

19 View Source File : EventStoreSnapshotStore.cs
License : Apache License 2.0
Project Creator : AkkaNetContrib

private ISnapshotAdapter BuildDefaultSnapshotAdapter()
        {
            Func<DefaultSnapshotEventAdapter> getDefaultAdapter = () => new DefaultSnapshotEventAdapter(_serialization);

            if (_settings.Adapter.ToLowerInvariant() == "default")
            {
                return getDefaultAdapter();
            }
            else if (_settings.Adapter.ToLowerInvariant() == "legacy")
            {
                return new LegacySnapshotEventAdapter();
            }

            try
            {
                var journalAdapterType = Type.GetType(_settings.Adapter);
                if (journalAdapterType == null)
                {
                    _log.Error(
                        $"Unable to find type [{_settings.Adapter}] Adapter for EventStoreJournal. Is the replacedembly referenced properly? Falling back to default");
                    return getDefaultAdapter();
                }

                var adapterConstructor = journalAdapterType.GetConstructor(new[] { typeof(Akka.Serialization.Serialization) });

                ISnapshotAdapter journalAdapter = (adapterConstructor != null
                    ? adapterConstructor.Invoke(new object[] { _serialization })
                    : Activator.CreateInstance(journalAdapterType)) as ISnapshotAdapter;
                if (journalAdapter == null)
                {
                    _log.Error(
                        $"Unable to create instance of type [{journalAdapterType.replacedemblyQualifiedName}] Adapter for EventStoreJournal. Do you have an empty constructor? Falling back to default.");
                    return getDefaultAdapter();
                }

                return journalAdapter;
            }
            catch (Exception e)
            {
                _log.Error(e, "Error loading Adapter for EventStoreJournal. Falling back to default");
                return getDefaultAdapter();
            }
        }

19 View Source File : DialogNodeEditor.cs
License : MIT License
Project Creator : alee12131415

public string LoadCanvas(string path) {
        //SAME AS SAVE CANVAS
        try {
            //EditorSaveObject load = Resources.Load(path) as EditorSaveObject;
            EditorSaveObject load = replacedetDatabase.LoadreplacedetAtPath(path, typeof(EditorSaveObject)) as EditorSaveObject;

            //build new CP / Index
            List<ConnectionPoint> CPIndex = new List<ConnectionPoint>();
            for (int i = 0; i < load.NumberOfCP; i++) {
                CPIndex.Add(new ConnectionPoint());
            }

            //build nodes
            int spent = 0; //tracks index of used CP
            nodes = new List<Node>();
            for (int i = 0; i < load.nodeinfos.Count; i++) {
                Type t = Type.GetType(load.nodeinfos[i].type);
                ConstructorInfo ctor = t.GetConstructor(new[] { GetType(), typeof(NodeInfo) });
                Node n = (Node)Convert.ChangeType(ctor.Invoke(new object[] { this, load.nodeinfos[i] }), t);
                n.Rebuild(CPIndex.GetRange(spent, load.NodeCPIndex[i]));
                spent += load.NodeCPIndex[i];
                AddNode(n);
            }

            //build connections
            connections = new List<Connection>();
            for (int i = 0; i < load.ConnectionIndexIn.Count; i++) {
                connections.Add(new Connection(CPIndex[load.ConnectionIndexIn[i]], CPIndex[load.ConnectionIndexOut[i]], RemoveConnection));
            }

            offset = new Vector2(load.offset.x, load.offset.y);
            drag = Vector2.zero;
        } catch (Exception e) {
            return e.Message;
        }
        return null;
    }

19 View Source File : EventStoreSagaRepository.cs
License : Apache License 2.0
Project Creator : alexeyzimarev

static TSaga SagaFactory()
        {
            var ctor = typeof(TSaga).GetConstructor(
                BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
                null, new Type[0], null);
            return (TSaga) ctor.Invoke(new object[0]);
        }

19 View Source File : EditorFactory.cs
License : MIT License
Project Creator : AlFasGD

public static T InitializeEditorComponent<T>(Bindable<Editor> editorBindable)
            where T : BasePluggableEditor
        {
            return typeof(T).GetConstructor(pluggableEditorConstructorParameterTypes).Invoke(new object[] { editorBindable }) as T;
        }

19 View Source File : EditorFactory.cs
License : MIT License
Project Creator : AlFasGD

private static PluggableEditorConstructor GetDelegateFromConstructor(ConstructorInfo info)
        {
            return editorBindable => info.Invoke(new object[] { editorBindable }) as BasePluggableEditor;
        }

19 View Source File : NativeMemory.cs
License : MIT License
Project Creator : allisterb

[MethodImpl(MethodImplOptions.AggressiveInlining)]
        public unsafe Vector<T> AsVector()
        {
            int count = Vector<T>.Count;
            if (!NumericTypes.Contains(CLRType))
            {
                throw new InvalidOperationException($"{CLRType.Name} is not a numeric type.");
            }
            else if (length != count)
            {
                throw new InvalidOperationException($"The length of the memory buffer must be {Vector<T>.Count} elements to create a vector of type {CLRType.Name}.");
            }
            else
            {
                Retain();
                object[] args = new object[2] { ptr, 0 };
                Vector<T> v = (Vector<T>)VectorInternalConstructorUsingPointer.Invoke(args);
                return v;
            }
        }

19 View Source File : DarkMeta.cs
License : MIT License
Project Creator : Alprog

public object CreateInstance()
        {
            if (ConstructorInfo == null)
            {
                Logger.Instance.Error(String.Format("No constructor at {0} darkmeta", Type.Name));
            }
            return ConstructorInfo.Invoke(EmptyArray<object>.Value);
        }

19 View Source File : DarkMeta.cs
License : MIT License
Project Creator : Alprog

public object CreateInstance(object arg)
        {
            if (ConstructorInfo == null)
            {
                Logger.Instance.Error(String.Format("No constructor at {0} darkmeta", Type.Name));
            }
            return ConstructorInfo.Invoke(new object[] { arg });
        }

19 View Source File : MemberFormatter.cs
License : MIT License
Project Creator : Alprog

public static MemberFormatter Create(MemberInfo memberInfo, SerializationFlags flags)
            {
                var dataType = GetDataType(memberInfo);
                var memberFormatter = typeof(MemberFormatter<>).MakeGenericType(dataType);
                var ctor = memberFormatter.GetConstructor(new Type[] { memberInfo.GetType(), typeof(SerializationFlags) });
                return ctor.Invoke(new object[] { memberInfo, flags }) as MemberFormatter;
            }

19 View Source File : MemberFormatter.cs
License : MIT License
Project Creator : Alprog

public static MemberFormatter CreateDistributed(MemberInfo memberInfo, SerializationFlags flags, string subPath)
            {
                var dataType = GetDataType(memberInfo);
                var memberFormatter = typeof(DistributedMemberFormatter<>).MakeGenericType(dataType);
                var ctor = memberFormatter.GetConstructor(new Type[] { memberInfo.GetType(), typeof(SerializationFlags), typeof(string) });
                return ctor.Invoke(new object[] { memberInfo, flags, subPath }) as MemberFormatter;
            }

19 View Source File : Extensions.cs
License : MIT License
Project Creator : Alprog

public static object InvokeDefaultConstructor(this Type type)
        {
            return type.GetDefaultConstructor().Invoke(EmptyArray<object>.Value);
        }

See More Examples